使用Javascript向iframe添加HTML5沙盒属性

7

我有一个空的iframe和一个按钮:

<input type="button" name="B1" value="google" onclick="frames['IFrameName1'].location.href='https://www.google.com/'">

但是(除了.location.href之外),我需要设置属性sandbox="allow-forms allow-scripts allow-same-origin,因为被嵌入的网站会“解框”。如何同时设置位置和沙盒?

2个回答

9

虽然您可以将iframe.sandbox属性设置为字符串,但它实际上是一个DOMTokenList接口,因此您也可以使用add()remove()单个令牌:

let myIframe = document.createElement('iframe');
myIframe.sandbox.add('allow-scripts');
myIframe.sandbox.toggle('allow-forms');

console.log(myIframe.sandbox.toString())
// Returns: "allow-scripts allow-forms"

console.log(myIframe.outerHTML)
// Returns: <iframe sandbox="allow-scripts allow-forms"></iframe>

5

如果你想在一个点击事件中同时执行两个操作,可以创建一个函数来完成这两个操作并在点击时触发该函数。

window.onload = function(){
    var button = document.getElementsByName("B1")[0]
    var iframe = document.getElementsByName("IFrameName1")[0]
    button.addEventListener('click',addSandboxAndChangeLocation,false);

    function addSandboxAndChangeLocation(){
       frames['IFrameName1'].location.href='https://www.google.com/';
       iframe.sandbox = 'allow-forms allow-scripts allow-same-origin';
    }
} 

点击这里在jsFiddle上查看!


谢谢,我正在尝试。也许使用jQuery会更容易? - Ivan
肯定会用jQuery更容易些。 - Adam
1
我担心沙盒没有应用,而且它继续解框,而纯HTML iframe则没有这个问题。 - Ivan
当然,我看到它在jsFiddle上运行。谢谢你的帮助和时间 ;) - Ivan
它无法被规避。这是一个安全特性。请参见https://dev59.com/kmox5IYBdhLWcg3whUgV - Adam
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接