打开和关闭镀铬扩展

时间:2013-11-15 21:08:50

标签: javascript google-chrome google-chrome-extension google-chrome-devtools

我正在使用Chrome扩展程序,此扩展程序在浏览器操作中有2个图标(On& Off); 基本上当它在后台执行script.js(注入文件:script.js) 使用chrome.tabs.executeScript(tab.id,{file:"script.js",function(){});

我有问题要把它关掉! 我试图在background.js和script.js之间使用消息通信,但这两种方法都不起作用。

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您的分机应该有两种状态,On和Off。单击扩展图标可以打开/关闭它。

在这种情况下,您应该使用存储,以便扩展名知道它处于什么状态。因此,在点击事件中,使用以下内容:

  chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.storage.sync.get('state', function(data) {
      if (data.state === 'on') {
        chrome.storage.sync.set({state: 'off'});
        //do something, removing the script or whatever
      } else {
        chrome.storage.sync.set({state: 'on'});
        //inject your script
      }
    });
  });

请注意,这种情况发生在扩展程序/浏览器级别并将应用于所有选项卡,因此您可能需要更复杂的内容来记录选项卡ID和状态。

然后,您可以选择始终运行内容脚本并在执行某些操作之前检查开/关状态,或者注入并删除脚本。我不确定你是否删除了一个脚本。根据脚本的功能,您可能只想刷新页面(例如,如果您的脚本与DOM混淆,并且您希望在关闭扩展时撤消该脚本)。

答案 1 :(得分:1)

background.js

var enable=false;
chrome.browserAction.onClicked.addListener(function (tab) {
 enable = enable ? false : true;
 if(enable){
  //turn on...
  chrome.browserAction.setIcon({ path: 'icon.png' });
  chrome.browserAction.setBadgeText({ text: 'ON' });
  chrome.tabs.executeScript(null, { file: 'content.js' }); 
 }else{
  //turn off...
  chrome.browserAction.setIcon({ path: 'disable.png'});
  chrome.browserAction.setBadgeText({ text: '' });
 }
});

答案 2 :(得分:0)

要添加@ david-gilbertson所说的使某些选项卡处于活动和非活动状态,我在这里创建了该功能。我还添加了一些功能,用于删除和添加标签到数组。享受吧!

function addTab(array, new_tab_id)
   {
    array.push(new_tab_id);
    //then call the set to update with modified value
    chrome.storage.sync.set({
        active_tabs:array
    }, function() {
        console.log("added tab");
    });
 }

function removeTab(array, rem_tab_id)
{
    const index = array.indexOf(rem_tab_id);
    if (index > -1) {
        array.splice(index, 1);
    }
    //then call the set to update with modified value
    chrome.storage.sync.set({
        active_tabs:array
    }, function() {
        console.log("removed tab");
    });
}

chrome.browserAction.onClicked.addListener(function (tab) {`enter code here`
  chrome.storage.sync.get({active_tabs : []}, function(data) {
      if (data.active_tabs.includes(request.tab_id)) {
        removeTab(data.active_tabs, request.tab_id)
        console.log("Turned Off ".concat(request.tab_id))
        document.removeEventListener("mousemove", highlightCurrentHover, false);
      } else {
        addTab(data.active_tabs, request.tab_id)
        console.log("Turned On ".concat(request.tab_id))
        document.addEventListener('mousemove', highlightCurrentHover, false);
      }
    });
);