Chrome扩展程序:是否可以在重新加载时保持扩展程序打开?

时间:2014-06-04 15:25:19

标签: google-chrome-extension reload

我正在构建一个在页面中插入html的Google扩展程序,并在浏览器操作图标点击时显示一个菜单,当我重新加载页面时,我找不到保持扩展程序打开的方法。因此,每次重新加载时,我们都必须从“浏览器操作”图标再次激活它。

清单文件

下方
{

    "background": {
        "scripts": ["background.js"]
    },

    "browser_action": {
        "default_icon": "img/icone.png",
        "default_title": "show menu"
    },

    "icons" : {
        "128" : "img/icone_128.png",
        "48" : "img/icone_48.png",
        "32" : "img/icone_32.png",
        "24" : "img/icone_24.png",
        "16" : "img/icone_16.png"
    },

    "manifest_version": 2,
    "name": "p|layer",
    "version": "1.0.4",

    "content_scripts": [
        {
            "matches": [ "<all_urls>"],
            "css":["css/grid.css", "css/font-awesome.min.css"],
            "js":["js/jquery-1.11.1.min.js","js/jquery-ui.js", "js/jquery.nicefileinput.min.js"]
        }
    ],

    "web_accessible_resources": [
        "fonts/fontawesome-webfont.woff"
    ],

    "permissions": [ "activeTab"]

 }

脚本( background.js )注入内容脚本

chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON

    chrome.tabs.executeScript(tab.id,
    {"file": "js/contentscript.js"},

    function () { // Execute your code
        console.log("Script Executed .. "); // Notification on Completion
    });

    chrome.tabs.insertCSS(tab.id, {file: "css/grid.css"});
    chrome.tabs.insertCSS(tab.id, {file: "css/font-awesome.min.css"});
    chrome.tabs.insertCSS(tab.id, {file: "css/slider.css"});

});

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

因此,从评论中推断出问题:您的按钮单击会激活您的内容脚本,但页面重新加载会清除它。假设您希望按钮单击以充当切换:

1)始终注入内容脚本/ CSS,但不要立即显示UI:

"content_scripts": [
  {
    "matches": [ "<all_urls>"],
    "css": ["css/grid.css", "css/font-awesome.min.css", "css/slider.css"],
    "js": [
      "js/jquery-1.11.1.min.js", "js/jquery-ui.js",
      "js/jquery.nicefileinput.min.js", "js/contentscript.js"
    ]
  }
],

2)跟踪“已激活”标签:

var activeTabs = {};

chrome.browserAction.onClicked.addListener( function(tab){
  var active;
  if(activeTabs[tab.id]){
    delete activeTabs[tab.id];
    active = false;
  } else {
    activeTabs[tab.id] = true;
    active = true;
  }

  /* (part 3) */
});

chrome.tabs.onRemoved.addListener( function(tabId){
  delete activeTabs[tabId];
});

chrome.tabs.onReplaced.addListener( function(newTabId, oldTabId){
  if(activeTabs[oldTabId]) activeTabs[newTabId] = true;
  delete activeTabs[oldTabId];
});

3)使用消息显示/隐藏UI:

内容脚本:

chrome.runtime.onMessage.addListener( function(message. sender, sendResponse){
  if(message.showUI) showUI();
  if(message.hideUI) hideUI();
});

后台脚本:

chrome.browserAction.onClicked.addListener( function (tab) {
  var active;
  /* (part 2) */

  if(active) {
    chrome.tabs.sendMessage(tab.id, {showUI: true});
  } else {
    chrome.tabs.sendMessage(tab.id, {hideUI: true});
  }
});

可以为扩展重新加载的情况添加额外的稳健性,但这是它的要点。