Created
November 11, 2015 16:53
-
-
Save mattkauffman23/691f8f167b009defc05f to your computer and use it in GitHub Desktop.
iframe sandboxing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sandboxDomain = 'https://different-domain.com' | |
function invokeCustomScript(scriptId) { | |
var iframe, sandbox; | |
iframe = document.createElement('iframe'); | |
iframe.src = sandboxDomain + '/custom-scripts/' + scriptId; | |
sandbox = iframe.contentWindow || iframe; | |
sandbox.postMessage({ method: 'init', state: gameState }, sandboxDomain); | |
} | |
window.addEventListener('message', function onSandboxMessage(evt) { | |
// Verify that we're handling messages from the sandbox domain | |
if (evt.origin !== sandboxDomain) { | |
return; | |
} | |
if (!customScriptApi[evt.data.method]) { | |
console.log('Error: Custom script attempted to call non-existant method ' + evt.data.method); | |
return; | |
} | |
customScriptApi[evt.data.method].apply(customScriptApi, evt.data.args); | |
}, false); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var parentDomain = 'https://main-domain.com', | |
parentWindow | |
var customScriptApi = { | |
doSomething: function doSomething() { | |
if (!parentWindow) { | |
throw new Error('Custom script sandbox not initialized'); | |
} | |
parentWindow.postMessage({ | |
method: 'doSomething', | |
args: Array.prototype.slice.call(arguments) | |
}, parentDomain); | |
} | |
} | |
window.addEventListener('message', function onParentMessage(evt) { | |
if (evt.origin !== parentDomain) { | |
return; | |
} | |
if (evt.data.method === 'init') { | |
parentWindow = evt.source; | |
userScript(customScriptApi, evt.data.state); | |
} | |
}, false); | |
// The user's script | |
function userScript(api, state) { | |
// Inspect state to determine what custom stuff to do... | |
api.doSomething('foo', 'bar', 'baz'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment