如何解决未捕获的类型错误:无法读取 chrome 扩展中未定义的属性“同步”清单 v3
我正在尝试将开关切换按钮集成到我的 Chrome 扩展程序(清单版本 3)中。却出现错误。
此代码基础基于以下链接:Chrome Extension set toggle switch state in all tabs
我收到以下错误消息:
未捕获的类型错误:无法读取未定义的属性“同步” 在 content.js:5
是的,manifest.json 中设置了“存储”,并且还重新加载和卸载了扩展作为测试。
似乎我通常无法在那里访问 chrome.storage。 可能是因为注入了 content.js 吗? 或者我是否需要为此使用消息传递 API?
popup.js
function setToggleState() {
chrome.storage.sync.get('isExtensionActive',storage => {
chrome.storage.sync.set({
isExtensionActive: !storage.isExtensionActive,});
});
}
document.addEventListener('DOMContentLoaded',function () {
var toggleBtn = document.getElementById('toggle-btn');
toggleBtn.addEventListener('click',function () {
setToggleState();
// here comes my code to set/toggle button text (on|off)
});
})
inject.js
function injectScript(file_path,tag) {
var node = document.getElementsByTagName(tag)[0];
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src',file_path);
node.appendChild(script);
}
injectScript(chrome.runtime.getURL('/components/content/content.js'),'body');
content.js
chrome.storage.sync.get('isExtensionActive',storage => {
toggleSomething(storage.isExtensionActive);
});
chrome.storage.onChanged.addListener(changes => {
if (changes.isExtensionActive) {
toggleSomething(changes.isExtensionActive.newValue);
}
});
function toggleSomething(state) {
console.log('new state:',state);
document.body.className = "state_" + state;
chrome.action.setBadgeText({
text: (state ? 'off' : '')
});
}
manifest.json
{
"manifest_version": 3,"name": "example","version": "0.0.1","description": "example","short_name": "example","permissions": ["tabs","activeTab","declarativeContent","storage","unlimitedStorage","contextMenus","alarms","notifications"],"host_permissions": ["<all_urls>"],"content_scripts": [{
"matches": ["https://example.com/*"],"css": ["/components/popup/popup.css","/components/content/content.css"],"js": ["/components/popup/popup.js","/components/content/inject.js"],"all_frames": true,"run_at": "document_end"
}],"web_accessible_resources": [{
"resources": ["/components/popup/popup.js","/components/content/inject.js","/components/content/content.css","chrome-extension://EXAMPLE-ID/content.css","/components/content/content.js","chrome-extension://EXAMPLE-ID/content.js"],"matches": ["<all_urls>"]
}],"options_ui": {
"page": "/components/options/options.html","open_in_tab": false
},"action": {
"default_title": "example title","default_popup": "/components/popup/popup.html","default_icon": {
"16": "icons/icon16.png","19": "icons/icon19.png","32": "icons/icon32.png","48": "icons/icon48.png","128": "icons/icon128.png"
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。