Add HTML5 sandbox attribute to an iframe using Javascript

前端 未结 2 642
抹茶落季
抹茶落季 2021-01-05 21:47

I\'ve got an empty iframe and a button:

相关标签:
2条回答
  • 2021-01-05 22:29

    If you want to do two things on one click event. Have a function do both of those things and fire that function on click.

    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';
        }
    } 
    

    Check it out on jsFiddle!

    0 讨论(0)
  • 2021-01-05 22:38

    While you can set the iframe.sandbox property as a string, it's technically a DOMTokenList interface, so you can also add() and remove() single tokens:

    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>
    
    0 讨论(0)
提交回复
热议问题