使用Javascript将HTML5沙箱属性添加到iframe

问题描述 投票:4回答:2

我有一个空的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,因为框架网站“deframes”。如何设置位置和沙箱?

javascript html5 iframe sandbox
2个回答
3
投票

如果您想在一次点击活动中做两件事。有一个函数可以执行这两个操作并在单击时激活该函数。

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上查看!


3
投票

虽然你可以将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>
© www.soinside.com 2019 - 2024. All rights reserved.