首页 > 解决方案 > 在 Chrome 或 Firefox 中禁用跨域框架

问题描述

我想要一个带有 iframe http://localhost:8080 的网络扩展。所以我可以测试我的选项页面。我想访问扩展 API。所以我不关心开发的安全性。

所以做了一个页面

chrome-extension://abcdefghijklmnopqrstuvw/page/index.html

<html>
<body>
<iframe id="myFrame" src="http://localhost:8080" crossorigin="anonymous">
</iframe>
<script src="script.js"></script>
</body>
</html>

本地主机:8080

<html>
<head>
</head>
<body>
<h1>I can't get this working :{</h1>
<script>
    console.log(parent);
</script>
</body>
</html>

我还发送了一个标题:“Access-Control-Allow-Origin”:“*”

当然我得到了这个错误:

DOMException: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.

我试图禁用网络安全

google-chrome-stable --disable-site-isolation-trials --disable-web-security --user-data-dir="~/tmp"

但是错误仍然存​​在。我还尝试了 web-ext 来禁用网络安全。

标签: google-chromeiframegoogle-chrome-extensionfirefox-addon-webextensionsweb-ext

解决方案


我做了一个简单的设置来测试我是否可以从另一个来源访问父对象。所以我有 http://localhost:1111 和 iframe http://localhost:2222。现在 :2222 正在调用 parent.testAlert(),在普通浏览器中,由于启用了安全性,这将被阻止。但是当我禁用安全性时,我可以访问 parent.testAlert() 。

<html>
<body>
One <br>
<script>
    function testAlert() {
        alert("Yes");
    }
    setTimeout(() => {
        console.log("window ", window.name);
    }, 1000)
</script>
<iframe src="http://localhost:2222"></iframe>
</body>
</html>
<html>
<body>
Two
<script>
    console.log("two: ");
    console.log("parent ", parent);
    parent.testAlert()
</script>
</body>
</html>

这仅在我禁用安全性时才有效,例如:

google-chrome-stable --disable-web-security --user-data-dir=~/tmp --disable-site-isolation-trails

好的。

现在让我们用 chrome-extension:// url 试试吧...

<html>
<body>
page.html
<iframe src="http://localhost:2222"></iframe>
</body>
</html>

我仍然得到同样的错误:

(index):7 Uncaught DOMException: Blocked a frame with origin "http://localhost:2222" from accessing a cross-origin frame.
at console.log (<anonymous>)
at http://localhost:2222/:7:13

似乎没有禁用 chrome 扩展 CORS / SOP。

我做了一个简单的例子https://github.com/zoutepopcorn/iframe-blocked


推荐阅读