首页 > 解决方案 > Chrome 扩展程序的内容脚本中的 XSS“阻止了来自访问跨域框架的框架”错误

问题描述

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

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

当加载的页面中有一个时,现在抛出以下异常IFRAME

阻止来源为“ https://www.youtube.com ”的框架访问跨域框架。

就像我说的那样,它曾经是获取扩展的顶部文档 URL 的方法(从content script. 那么现在公认的方法是什么?

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

编辑:此脚本content_scriptsmanifest.json定义如下的中运行:

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

标签: javascriptgoogle-chromegoogle-chrome-extensionxss

解决方案


内容脚本应该要求您的后台脚本通过消息传递来执行此操作:

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

后台脚本应该在 manifest.json 中声明:

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

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

"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;
  }
});

推荐阅读