简体   繁体   English

在页面重新加载时继续运行Chrome扩展程序

[英]Keep Chrome Extension running on page reload

I'm trying to build a simple chrome extension that inserts/hides a div when the browser action (extension icon) is toggled. 我正在尝试构建一个简单的chrome扩展,在切换浏览器操作(扩展图标)时插入/隐藏div。 I've got the basics working but I would like the extension to remain in it's 'on-state' (ie div inserted) when the page reloads. 我已经掌握了基础知识,但我希望扩展在页面重新加载时保持在“on-state” (即插入div)。 It should only be removed when toggled off. 它只应在切换时删除。

Currently on each reload everything resets. 目前每次重新加载都会重置。

Here's what I have so far: 这是我到目前为止所拥有的:

manifest.json 的manifest.json

{
    "name": "My Extension",
    "version": "0.0.1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_icon": "icon-off.png"
    },
    "permissions": [
        "tabs"
    ]
}

background.js background.js

toggle = false;

chrome.browserAction.onClicked.addListener(function(tab) {

    toggle = !toggle;

    var status = 'off';

    if(toggle) {
        status = 'on';
    }

    // Toggle the icon
    chrome.browserAction.setIcon({path: 'icon-'+status+'.png', tabId:tab.id});

    // Execute script & pass a variable
    chrome.tabs.executeScript(tab.id, {
        code: 'var extension_status = "'+status+'";'
    }, function() {
        chrome.tabs.executeScript(tab.id, {file: 'inject.js'});
    });

});

inject.js inject.js

// ID for inserted element
var my_div_id = 'foo';

// The div (returns null if doesn't exist)
var my_div = document.getElementById(my_div_id);

// If on for first time
if( extension_status == 'on' && !my_div ) {

    // Create div
    var div = document.createElement('div');
    div.id = my_div_id;
    div.textContent = 'hello';

    // Insert into page
    document.body.appendChild(div);

}
// When toggled off hide
else if( extension_status == 'off' ) {
    my_div.style.display = 'none';
}
// When Toggled back on again show again
else {
    my_div.style.display = 'block';
}

Do I need to pass a value back to my background.js file? 我需要将值传递回我的background.js文件吗? or is there a better way to handle this? 还是有更好的方法来处理这个问题?

I did eventually figure out that I needed to add a listener for chrome.tabs.onUpdated as @ViewSource's excellent answer also stated. 我最终弄清楚我需要为chrome.tabs.onUpdated添加一个监听器,因为@ ViewSource的优秀答案也说明了。 Here's the final working example: 这是最后的工作示例:

manifest.json 的manifest.json

{
    "name": "My Extension",
    "version": "0.0.1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_icon": "icons/icon-off.png"
    }
    "permissions": [
        "activeTab",
        "<all_urls>"
    ]
}

background.js background.js

var toggle = false;
var status = 'off';
var the_tab_id = '';

function set_status() {
    toggle = !toggle;
    status = 'off';
    if(toggle) { status = 'on'; }
}

function toggle_extension(tab){
    // Set icon
    chrome.browserAction.setIcon({ path: 'icons/icon-'+status+'.png', tabId:tab.id });
    // Pass variable & execute script
    chrome.tabs.executeScript({ code: 'var extension_status = "'+status+'"' });
    chrome.tabs.executeScript({ file: 'inject.js' });
    // Set the tab id
    the_tab_id = tab.id;
}

function my_listener(tabId, changeInfo, tab) {
    // If updated tab matches this one
    if (changeInfo.status == "complete" && tabId == the_tab_id && status == 'on') {
        toggle_extension(tab);
    }
}

chrome.browserAction.onClicked.addListener(function(tab) {
    set_status();
    toggle_extension(tab);
});

chrome.tabs.onUpdated.addListener(my_listener);

inject.js inject.js

if( extension_status == 'on' ) {
    // do stuff
}

I had the same problame myself. 我自己也有同样的问题。

After the page reload, you need to toggle the extension again, as you did when the user push the browserAction button, just without the - toggle = !toggle; 页面重新加载后,您需要再次切换扩展名,就像用户按下browserAction按钮时一样,只需要 - toggle = !toggle; because the user didn't change the extension's state. 因为用户没有改变扩展的状态。

So, how do you know when the tab reload? 那么,你怎么知道标签何时重新加载? using tabs.onUpdated 使用tabs.onUpdated

Your new background page should look like this: 您的新背景页应如下所示:

var toggle = false;
var status = 'off';

chrome.browserAction.onClicked.addListener(function(tab) {
     set_status();
     toggle_extansion()
});

//add listener
chrome.tabs.onUpdated.addListener(your_listener);

function your_listener(tabId, changeInfo, tab) {
  //Check that the extension should work on the updated tab
  if (tab.url.search("://www.thesite.com") >-1){
    //toggle the extansion as you already did
    toggle_extansion();
  }
}

function toggle_extansion(){
   // Toggle the icon
   chrome.browserAction.setIcon({path: 'icon-'+status+'.png', tabId:tab.id});

   // Execute script & pass a variable
   chrome.tabs.executeScript(tab.id, {
       code: 'var extension_status = "'+status+'";'
   }, function() {
       chrome.tabs.executeScript(tab.id, {file: 'inject.js'});
   });
}

function set_status(){
    toggle = !toggle;

    if(toggle) {
        status = 'on';
    }
}

Note: There is no easy way to listen only to tabs containig the matches sites in your extension's manifest. 注意:没有简单的方法可以只收听扩展程序清单中包含匹配网站的标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM