I have a basic website located in A.html
<body>
<p class="text">Some text</p>
</body>
There is also another site that displays A within an iframe on B.html
<body>
<iframe id="frame" src="B.html" onload="onLoadHandler();"></iframe>
</body>
When I open file B in Google Chrome, everything appears as expected. However, when I attempt to change the color of the p element in the iframe to pink using the following line of Javascript code in B.html:
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 encounter an 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 test scenario, but consider a real case where we have a website www.company.com running in an iframe with www.verysecurebank.com. We want to customize the style of some buttons inside that iframe. The domains will not match in this situation.
I find it puzzling that browsers view this as cross-site scripting, while in developer tools (F12), we can manipulate the DOM of any part of the iframe without issue. We were able to turn all buttons in the iframe blue using developer tools, but Javascript in the parent HTML containing the iframe cannot achieve the same result.