Skip to content

Instantly share code, notes, and snippets.

@mohamedmansour
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohamedmansour/dc0c56820015e7f700e9 to your computer and use it in GitHub Desktop.
Save mohamedmansour/dc0c56820015e7f700e9 to your computer and use it in GitHub Desktop.
Basic Cross Sandbox Communication for iOS 8 Action Extensions
// Append the transfer dom to the document.
var transferDOM = document.createElement('div');
transferDOM.style.display = 'none';
transferDOM.id = 'transferdom';
document.body.appendChild(transferDOM);
function injectScript(fn) {
var script = document.createElement('script');
script.appendChild(document.createTextNode('(' + fn + ')();'));
document.body.appendChild(script);
}
function someScripToInjectIntoBrowserContext() {
(function() {
var transferDOM = document.getElementById("transferdom");
window.Microsoft = "assigned";
console.log("Browser Context : window.Microsoft = " + window.Microsoft);
window.addEventListener('ExtensionContextEvent', onMessageReceived);
// Script is ready inform the extension context.
function dispatch(msg) {
console.log("Browser Context : Dispatching: " + msg);
transferDOM.innerText = msg;
var transferEvent = document.createEvent('Event');
transferEvent.initEvent('BrowserContextEvent', true, true);
window.dispatchEvent(transferEvent);
}
dispatch("ready");
function onMessageReceived() {
var data = transferDOM.innerText;
console.log("Browser Context : DataReceived : " + data);
dispatch("Microsoft = " + window.Microsoft);
}
})();
}
function dispatch(msg) {
console.log("Extension Context : Dispatching: " + msg);
transferDOM.innerText = msg;
var transferExtensionEvent = document.createEvent('Event');
transferExtensionEvent.initEvent('ExtensionContextEvent', true, true);
window.dispatchEvent(transferExtensionEvent);
}
window.addEventListener('BrowserContextEvent', onMessageReceived);
function onMessageReceived() {
var data = transferDOM.innerText;
console.log("Extension Context : DataReceived : " + data);
if (data == 'ready') {
// Dispatch an event to fetch the Microsoft variable.
dispatch("fetch");
}
}
console.log("Extension Context : window.Microsoft = ", window.Microsoft);
// Injects some code into the Browser Context
injectScript(someScripToInjectIntoBrowserContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment