Chrome 扩展的内容脚本中的 XSS "Blocked a frame with origin from accessing a cross-origin frame" 错误

XSS "Blocked a frame with origin from accessing a cross-origin frame" error in content script for a Chrome extension

我在 Google Chrome 商店中使用此扩展已有一段时间了。进行维护更新后,我注意到 content.js(内容脚本)中的以下行:

//Get top document URL (that is the same for all IFRAMEs)
var strTopURL = window.top.document.URL;

现在在加载的页面中包含 IFRAME 时抛出以下异常:

Blocked a frame with origin "https://www.youtube.com" from accessing a cross-origin frame.

正如我所说,它曾经是为您的扩展获取顶级文档 URL 的方式(来自 content script)。那么现在接受的方法是什么?

PS。同样,我说的是 Google Chrome 扩展(而不仅仅是页面上的常规 JS。)

编辑: 该脚本在 manifest.json 中的 content_scripts 下 运行 定义如下:

"content_scripts": [
    {
        "run_at": "document_end",
        "all_frames" : true,
        "match_about_blank": true,
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]
    }
],

内容脚本应该通过消息请求您的后台脚本来完成:

chrome.runtime.sendMessage('getTopUrl', url => {
  // use the URL here inside the callback or store in a global variable
  // to use in another event callback that will be triggered in the future
  console.log(url);
});
// can't use it right here - because the callback runs asynchronously

background script 应在 manifest.json 中声明:

"background": {
  "scripts": ["background.js"],
  "persistent": false
},

您还需要 manifest.json 中的特定 URL 权限或允许所有 URLs:

"permissions": ["<all_urls>"]

以及后台脚本中的监听器:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg === 'getTopUrl') {
    chrome.tabs.get(sender.tab.id, tab => sendResponse(tab.url));
    // keep the message channel open for the asynchronous callback above
    return true;
  }
});