Search code examples
javascripthtmliframesandbox

Add HTML5 sandbox attribute to an iframe using Javascript


I've got an empty iframe and a button:

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

But (besides .location.href) i need to set the attribute sandbox="allow-forms allow-scripts allow-same-origin, because the framed site "deframes". How to set location AND sandbox?


Solution

  • 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!