如何使用沙箱将jQuery事件附加到iframe? [英] How to append jQuery events to an iframe with sandbox?

查看:310
本文介绍了如何使用沙箱将jQuery事件附加到iframe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iframe加载本地页面(代理):我需要这些页面中的javascript不被执行(我已经在服务器上执行它,在客户端再次执行它会导致双重执行,因此很糟糕) 。

I have an iframe which loads local pages (proxy): I need the javascript in these pages not to be executed (I am already executing it on the server, executing it again in the client leads to double execution, therefore bad).

我可以通过使用新的沙盒参数来实现这一点。

I can achieve this by using the new "sandbox" argument.

我需要的是能够将主窗口中的事件添加到iframe内容中。这似乎不起作用。

The catch is that I need to be able to add events from the main window to the iframe contents. This does not seem to work.

我使用的jsfiddle

<iframe 
id='iframe1' 
sandbox='allow-top-navigation allow-same-origin allow-forms'
srcdoc='<html><head></head><body><div id="test">iframe1</div><script>document.body.style.backgroundColor="yellow"</script></body></html>'>
</iframe>

<iframe
id='iframe2'
srcdoc='<html><head></head><body><div id="test">iframe2</div><script>document.body.style.backgroundColor="yellow"</script></body></html>'>
</iframe>

-

$('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更改其内容。

As you can see, frame1 is sandboxed and does not execute internal JS (background does not become yellow). However, I can change its contents using JS in the parent window.

有没有办法添加活动?如果没有,将页面加载到iframe而不让它执行其javascript的最佳方法是什么?

Is there a way to add events, too? If not, what would be the best way to load a page into an iframe without letting it execute its javascript?

推荐答案

附加事件沙箱iframe的内容与从iframe运行javascript相同,因此无法完成。

Attaching events to the content of a sandboxed iframe is the same as running the javascript from the iframe, hence it cannot be done.

我通过预先添加来解决停止JS执行的问题以下文件的< head>

I solved the problem of stopping JS execution by prepending in the <head> of the document the following:

<script>Function.prototype.call = Function.prototype.apply = function(){};</script>

编辑:看起来这还不够。我最终决定从文档中删除< script> 块。

it seems like this is not enough. I finally decided to simply strip the <script>blocks from the document.

这篇关于如何使用沙箱将jQuery事件附加到iframe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆