Skip to content
Advertisement

How to automatically add a sandbox attribute to iframe using JS

I have multiple video players on my site, but they open popup ads, so to block them I use the sandbox attribute, but not all of the players have the sandbox attribute. So I need javascript to automatically add the sandbox="allow-modals allow-orientation-lock allow-pointer-lock allow-presentation allow-scripts allow-top-navigation allow-forms attribute to all iframes on the page. How can I do this? Help would be highly appreciated! Thanks!

Advertisement

Answer

You can select all the frames in a page by using getElementsByTagName, loop over them, and set the attribute of a DOM element by using Element.setAttribute:

var frames = document.getElementsByTagName('iframe');
for (var frame of frames) {
    frame.setAttribute("sandbox", "allow-modals allow-orientation-lock allow-pointer-lock allow-presentation allow-scripts allow-top-navigation allow-forms");
}

jsfiddle example here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement