如何使用沙箱将jQuery事件附加到iframe?
我有一个iframe加载本地页面(代理):我需要这些页面中的javascript不被执行(我已经在服务器上执行它,在客户端再次执行它会导致双重执行,因此很糟糕)。
我可以通过使用新的“沙盒”参数来实现这一点。
问题是,我需要能够将主窗口中的事件添加到iframe内容中。 这似乎不起作用。
我用jsfiddle准备了一个例子。
<iframe id='iframe1' sandbox='allow-top-navigation allow-same-origin allow-forms' srcdoc='iframe1document.body.style.backgroundColor="yellow"'> <iframe id='iframe2' srcdoc='iframe2document.body.style.backgroundColor="yellow"'>
–
$('iframe').load(function() { var id = this.id; //this works in both iframes $(this).contents().find("#test").html(id+" says gnek!"); //I need this to work for iframe 1, too. $(this).contents().on("click", function(event) { alert("clicked "+id); }); });
如您所见,frame1是沙箱,不执行内部JS(背景不会变黄)。 但是,我可以在父窗口中使用JS更改其内容。
有没有办法添加活动? 如果没有,将页面加载到iframe而不让它执行其javascript的最佳方法是什么?
将事件附加到沙盒iframe的内容与从iframe运行javascript相同,因此无法完成。
我通过在文档的中加上以下内容来解决停止JS执行的问题:
编辑:似乎这还不够。 我终于决定从文档中删除块。