用于 chrome 扩展的 iFrame 的跨域问题

Jos*_*osh 5 javascript iframe cross-domain google-chrome-extension

我正在尝试为 Google Hangouts 中的自动拨号编写一个 chrome 扩展,这样我就不必为每次会议输入我的会议桥号码。也能保存它们会很好……无论如何,我的概念有点工作,但我正在尝试解决跨域问题。

在 Google Hangouts 中拨打电话时,您会从联系人页面开始,然后输入要拨打的号码。当您按 Enter 键或单击“拨打电话”时,拨号程序将加载到 iFrame 中。在我的 chrome 扩展中,我能够获得对 iFrame 的引用,但是 Frame 位于域“plus.google.com”下,并且我的脚本正在从“hangouts.google.com”访问。

我知道它们都在 google.com 父域下,所以我试图允许我的 chrome 扩展访问框架,以便在框架的 contentWindow 中的拨号器按钮上执行 .click() 。

在 chrome 扩展的内容脚本中,我从父页面中选择 iframe 元素并将其设置为名为 iframe 的变量。

var iframe = $("div iframe")[0];
Run Code Online (Sandbox Code Playgroud)

我可以设置

document.domain = "google.com";
Run Code Online (Sandbox Code Playgroud)

没有问题,但是当我尝试做

iframe.contentWindow.document.domain = "google.com";
Run Code Online (Sandbox Code Playgroud)

我得到

content.js:3 Uncaught SecurityError: Blocked a frame with origin 
"https://hangouts.google.com" from accessing a frame with origin 
"https://plus.google.com". The frame requesting access set "document.domain" to 
"google.com", but the frame being accessed did not. Both must set 
"document.domain" to the same value to allow access.
Run Code Online (Sandbox Code Playgroud)

我试过放宽扩展程序中的内容安全策略,但也许我做得不对:

  "content_security_policy": "script-src 'self' https://google.com; object-src 'self'",
  "permissions": [
    "http://*/",
    "tabs"
  ]
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题?

Xan*_*Xan 1

在这种情况下,添加权限或放宽 CSP 不会有帮助。

您需要 iframe 中内容脚本的第二个实例来跨域操作其文档。

确保您使用"all_frames": true.

您可以使用 来在内容脚本之间进行通信iframe.contentWindow.postMessage