简体   繁体   中英

Editing the DOM of an iframe by using javascript in the parent

So I have a very simple website in A.html

<body>
    <p class="text">Some text</p>
</body>

And another site that shows A in an iframe in B.html

<body>
    <iframe id="frame" src="B.html" onload="onLoadHandler();"></iframe>
</body>

If I open file B in my google chrome browser, everything is shown as intended. However, If I execute the following line of javascript code in B.html (trying to change the color of p element in the iframe to pink)

function onLoadHandler()
{
    var frameElement = document.getElementById('frame');
    var frameDocument = frameElement.contentWindow ? frameElement.contentWindow : frameElement.contentDocument.defaultView;

    var x = frameDocument.getElementsByClassName("text");
    x[0].style.backgroundColor = "pink";
}

I get the following error at the second line:

Uncaught SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

This was just a dummy test, the real scenario is we have website www.company.com, and in an iframe runs www.verysecurebank.com, and we want to edit the style of some buttons inside that iframe. So yeah, domains will never match.

I'm wondering though, why is this considered cross site scripting by browsers, but if you go to developer tools (f12) you can manipulate the dom of any part of the iframe without problems in the browser itself? We could succesfully turn all buttons in the iframe blue using the developer tools, but we can't achieve it with javascript in the parent html that contains the iframe.

The three rules to judge if there is a cross-domain:

  1. different protocol;
  2. different port;
  3. different domain name.

The first one and the second one can not be solved by front end developers. As the last one, if the two domain have the same main domain name, it can be solved by set the document.domain to the same main domain name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM