简体   繁体   English

使用父级中的javascript编辑iframe的DOM

[英]Editing the DOM of an iframe by using javascript in the parent

So I have a very simple website in A.html 所以我在A.html中有一个非常简单的网站

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

And another site that shows A in an iframe in B.html 另一个网站在B.html的iframe中显示A

<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. 如果我在Google chrome浏览器中打开文件B,则一切都会按预期显示。 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) 但是,如果我在B.html中执行以下JavaScript代码行(尝试将iframe中p元素的颜色更改为粉红色)

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". 未捕获到的SecurityError:阻止了源为“ null”的帧访问源为“ 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. 这只是一个虚拟测试,真正的场景是我们拥有网站www.company.com,并且在iframe中运行www.verysecurebank.com,我们希望编辑该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? 不过,我想知道为什么浏览器会将此视为跨站点脚本,但是如果您使用开发人员工具(f12),则可以操纵iframe的任何部分,而浏览器本身不会出现问题? 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. 我们可以使用开发人员工具将iframe中的所有按钮成功设为蓝色,但是我们无法使用包含iframe的父html中的javascript实现它。

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. 作为最后一个,如果两个域具有相同的主域名,则可以通过将document.domain设置为相同的主域名来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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