问题描述
我正在尝试将开关切换按钮集成到我的 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 (将#修改为@)