1

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.

user1884155
  • 3,616
  • 4
  • 55
  • 108
  • 1
    I suspect you are running this with local file URLs which some browsers consider a "null" origin and won't let you do common things on other frames. If you run this on an actual web server you will probably not have this issue. Or some browsers allow to temporarily disable this security check for file:// URLs for testing purposes. – jfriend00 Apr 13 '15 at 15:28
  • @Teemu Are you sure the link you posted is relevant? If so, which part exactly? – user1884155 Apr 13 '15 at 15:28
  • I'm sorry, picked a wrong link from my bookmarks, [this](http://stackoverflow.com/questions/5660116/unsafe-javascript-attempt-to-access-frame-in-google-chrome) was the intended-one. – Teemu Apr 13 '15 at 15:30

1 Answers1

0

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.

yibuyisheng
  • 149
  • 8