Chrome Extension to show a toggle to enable/disable extension

≯℡__Kan透↙ 提交于 2020-03-16 09:17:05

问题


Here is my manifest

{
    "name": "my-extension",
    "version": "0.0.9",
    "manifest_version": 2,
    "icons": {
        "16": "img/icon16.png",
    },
    "browser_action": {
        "default_icon": "img/icon16.png",
        "default_popup": "html/popup.html"
    },
    "web_accessible_resources": [
        "data/links.json"
    ],
    "content_scripts": [...],
    "background": {
        "scripts": [
            "js/background.js"
        ]
    },
    "permissions": [
        "tabs",
    ]
}

I'd like a toggle to be in html/popup.html so that when the user clicks it, I can store some boolean to know if my extension is enabled or disabled. Then in the content_scripts I can use this boolean to know whether to perform tasks or not.

So far I have a basic html/popup.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>

<body id="popup">
    <button>
        <!-- Somehow add a text on/off here based on the state -->
    </button>
</body>
</html>

回答1:


You can use chrome.storage API to synchronise the information between your popup and your content script. For example:

popup.html

<body>
    <button id="toggle"></button>
    <script src="popup.js"></script>
</body>

popup.js

var enabled = false; //disabled by default
var myButton = document.getElementById('toggle');

chrome.storage.local.get('enabled', data => {
    enabled = !!data.enabled;
    myButton.textContent = enabled ? 'Disable' : 'Enable';
});

myButton.onclick = () => {
    enabled = !enabled;
    myButton.textContent = enabled ? 'Disable' : 'Enable';
    chrome.storage.local.set({enabled:enabled});
};

content_script.js

chrome.storage.local.get('enabled', data => {
    if (data.enabled) {
        //it is enabled, do accordingly
    } else {
        //it is disabled
    }
});


来源:https://stackoverflow.com/questions/54727978/chrome-extension-to-show-a-toggle-to-enable-disable-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!