Chrome MV3:如何在注入脚本中读取chrome.storage数据?
MV3 Chrome扩展:注入脚本读取语言设置的问题与解决办法
我在开发基于Manifest V3的Chrome扩展时,遇到了一个场景:用户在扩展弹窗中选择语言,需要让注入到目标网站的脚本读取这个语言设置,但碰到了几个障碍:
- 注入脚本无法访问
chrome.storage.sync,也无法使用Chrome的消息通信API - 尝试在内容脚本中设置全局变量,注入脚本同样读取不到
相关代码示例
manifest.json
{ "manifest_version": 3, "permissions": ["storage"], "background": { "service_worker": "js/service_worker.js" }, "content_scripts": [ { "matches": ["*://.../*"], "js": ["js/content-script.js"] } ], "web_accessible_resources": [ { "resources": ["js/inject.js"], "matches": ["*://.../*"] } ], "action": { "default_popup": "popup/popup.html" } }
content-script.js
function importScript(src) { let s = document.createElement('script'); s.src = chrome.runtime.getURL(src); s.onload = function() { this.remove(); }; (document.head || document.documentElement).appendChild(s); } window.hi = "test" // 注入脚本里读不到这个变量... importScript("js/inject.js")
inject.js
chrome.storage.sync.get() // 结果是undefined window.hi // 结果也是undefined
解决办法
再次查阅文档后发现,内容脚本和注入脚本之间可以通过window.postMessage来传递消息,用这个方法顺利解决了问题。
内容的提问来源于stack exchange,提问作者bananajoey88
相关产品推荐
相关产品推荐

