做这样的事情:
清单.json
"sandbox": {
"pages": ["my_ui.html"]
}
my_ui.html
<script type="text/javascript" src="knockout-1.2.3.4.js"></script>
<script type="text/javascript" src="my_ui.js"></script>
my_ui.js
this.onSomethingChange = function() {
window.top.postMessage(
{ command: 'please-do-something', myArgument: this.myArgument() }, '*');
};
容器.html
<script type="text/javascript" src="container.js"></script>
<iframe id="knockoutFrame" src="my_ui.html"></iframe>
容器.js
window.addEventListener('message', function(event) {
var kocw = document.getElementById('knockoutFrame').contentWindow;
var anotherContentWindow = // etc.
var dest;
if (event.source == kocw) {
// The knockout iframe sent us a message. So we'll forward it to our
// app code.
dest = anotherContentWindow;
}
if (event.source == anotherContentWindow) {
// Our app code is responding to the knockout message (or initiating
// a conversation with that iframe). Forward it to the knockout code.
dest = kocw;
}
if (dest == null) {
console.log('huh?');
}
// This makes container.js like a gatekeeper, bouncing valid messages between
// the sandboxed page and the other page in your app. You should do
// better validation here, making sure the command is real, the source
// is as expected for the kind of command, etc.
dest.postMessage(event.data, '*');
}
您的声明“我必须将真正的 application.html 定义为沙盒页面并将其作为 iframe 包含在虚拟容器中”可能不是您想要的。这个想法是将尽可能小的东西沙箱化,将消息发送到验证消息的网守页面,并让网守将窄消息转发到您的未沙箱化应用程序逻辑。如果你只是把所有东西都塞进沙箱,你就违背了沙箱的目的。
免责声明:我没有从安全角度仔细检查此代码。您需要假设恶意消息来自沙箱(或其他地方,就此而言),并尽您所能解决该威胁。