扩展can't访问窗口对象中的自定义函数

Extension can't access to custom functions in window object

本文关键字:对象 窗口 自定义函数 访问 can 扩展      更新时间:2023-09-26

当Chrome扩展试图通过Chrome.executeScript在窗口对象中获取自定义函数时,它一无所获。

例如:

选项卡ID:150

选项卡js:

window.customfunc = function(){return 'yeap';}

扩展的后台JS:

chrome.tabs.executeScript(150, { code: "console.log(window);" })

Manifest.json:

{
   "background": {
      "scripts": [ "background.js" ]
   },
   "content_scripts": [ {
      "exclude_globs": [  ],
      "exclude_matches": [  ],
      "include_globs": [ "*://*/*" ],
      "js": [ "script.js" ],
      "matches": [ "http://*/*" ],
      "run_at": "document_idle"
   } ],
   "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
   "description": "Test",
   "manifest_version": 2,
   "name": "Workspace",
   "permissions": [ "unlimitedStorage", "notifications", "clipboardWrite", "notifications", "clipboardRead", "management", "tabs", "history", "cookies", "idle", "storage", "webRequest", "webRequestBlocking", "contentSettings", "*://*/*" ],
   "version": "1.0"
}

结果:

在控制台中,window对象不显示customfunc,因此我们不能将window.customfuncchrome.executeScript一起使用。

为什么会发生这种情况,我们该如何解决?谢谢

这是为了安全。内容脚本(background.js正在执行)与选项卡的脚本(定义了customfunc)隔离。您还可以获得额外的好处,即不必担心命名空间冲突(这就是您的问题所在)。

一种方法是创建
myscript.js,它说
console.log(window)
然后使用内容脚本(或chrome.tabs.executeScript)编写
<script src='chrome.extension.getURL("myscript.js")'></script>
到选项卡的DOM。您还需要添加
"web_accessible_resources": ["myscript.js"]
到你的清单。

但由于事情如此复杂,一个很好的问题是为什么您需要访问customfunc。(你也可以看看https://stackoverflow.com/a/9517879/2336725更长的答案。)