【问题标题】:Add HTML5 sandbox attribute to an iframe using Javascript使用 Javascript 将 HTML5 沙盒属性添加到 iframe
【发布时间】:2012-10-22 23:34:08
【问题描述】:

我有一个空的 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 html iframe sandbox


    【解决方案1】:

    虽然您可以将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>
    

    【讨论】:

      【解决方案2】:

      如果你想在一次点击事件上做两件事。让一个函数同时完成这两件事并在点击时触发该函数。

      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 会不会更容易?
      • 使用 jQuery 肯定会更容易。
      • 恐怕沙盒没有应用,它继续去帧,而纯 HTML iframe 没有。
      • 我想我看到了我们的问题。我们必须在 iframe dom 元素上设置沙盒属性,而不是框架本身。
      • 当然,我看到它正在 jsFiddle 上运行。感谢您的帮助和时间;)
      猜你喜欢
      • 2019-02-18
      • 2012-11-04
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多