简体   繁体   English

以编程方式在扩展程序上注入内容脚本(Chrome扩展程序)

[英]Inject content script on extension reload programmatically (chrome extension)

I am creating a chrome extension that I want to be able to enable/disable. 我正在创建一个我希望能够启用/禁用的Chrome扩展程序。 I have successfully made a popup that does just that. 我已经成功制作了一个弹出窗口,可以做到这一点。 The trouble is, if I reload the extension (or if the user downloads it initially) my content scripts default to being off. 问题是,如果我重新加载扩展(或者如果用户最初下载了该扩展),则我的内容脚本默认为关闭。 I could just inject the content script in the manifest.json but that results in the content script being injected for any new tab--which I do not want. 可以只将内容脚本注入manifest.json中,但这会导致为任何新选项卡注入内容脚本,这是我不想要的。 The behavior should be that if you download/reload the extension, it is on by default, but then you can enable it/disable it and that applies to every new tab. 行为应该是,如果您下载/重新加载该扩展程序,则默认情况下它处于打开状态,但是您可以启用/禁用它,并且该扩展名适用于每个新选项卡。 I have tried to put an initialization in background.js but that does not get called at startup apparently. 我尝试将初始化放在background.js中,但显然在启动时未调用该初始化。

manifest.json manifest.json

{
  "manifest_version": 2,
  "name": "Rotten Tomatoes Search",
  "description": "This extension searches rotten tomatoes with highlighted text",
  "version": "1.0",
  "browser_action": {
    "default_icon": "./icons/icon_on.png",
    "default_popup": "popup.html"
  },
  "permissions": [
      "activeTab",
      "<all_urls>",
      "background"
  ],
   "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "content_scripts": [{
     "js": ["jquery-1.12.3.min.js"], 
     "matches": ["<all_urls>"]
   }]
}

background.js background.js

var isExtensionOn = true;
chrome.tabs.executeScript({code: "console.log('backgournd hit...')"});

turnItOn();

chrome.extension.onMessage.addListener(
function (request, sender, sendResponse) {
    if (request.cmd == "setOnOffState") {
        isExtensionOn = request.data.value;
    }

    if (request.cmd == "getOnOffState") {
        sendResponse(isExtensionOn);
    }
});

function turnItOn() {
    chrome.browserAction.setIcon({path: "./icons/icon_on.png"});
    chrome.tabs.executeScript({file:"openTooltipMenu.js"});
    //$('#toggle').text('disable');
}

popup.js popup.js

document.addEventListener('DOMContentLoaded', function() {
// show different text depending on on/off state (for icon, handled by having default icon)
 chrome.extension.sendMessage({ cmd: "getOnOffState" }, function(currentState){
    if (currentState) $('#toggle').text('disable');
    else $('#toggle').text('enable');
 });
// allow user to toggle state of extension
var toggle = document.getElementById('toggle')
toggle.addEventListener('click', function() {
    //chrome.tabs.executeScript({code: "console.log('toggled...')"});
    chrome.extension.sendMessage({ cmd: "getOnOffState" }, function(currentState){
        var newState = !currentState;
        // toggle to the new state in background
        chrome.extension.sendMessage({ cmd: "setOnOffState", data: { value: newState } }, function(){
            // after toggling, do stuff based on new state
            if (newState) turnOn();
            else turnOff();
        });
    });
})
});

function turnOn() {
    chrome.browserAction.setIcon({path: "./icons/icon_on.png"});
    chrome.tabs.executeScript({file:"openTooltipMenu.js"});
    $('#toggle').text('disable');
}

function turnOff() {
    chrome.browserAction.setIcon({path: "./icons/icon_off.png"});
    chrome.tabs.executeScript({code: "$('body').off();"});
    $('#toggle').text('enable');
}

popup.html popup.html

<some code>
    <script src="./jquery-1.12.3.min.js"></script>
    <script src="./popup.js"></script><style type="text/css"></style>
  </head>
  <body>
    <div class="popupMenu" style="list-style-type:none">
      <div class="header">Rotten Tomatoes Search</div>
      <hr>
      <div class="menuEntry" id="toggle"></div>
    </div>
  </body>
</html>

I have figured out the issue. 我已经解决了这个问题。 My architectural approach was wrong. 我的架构方法是错误的。 One should inject the content_script globally but check with the script whether or not something should be done. 一个人应该全局注入content_script,但要检查脚本是否应该执行某些操作。 To be clearer, in the script get the status from the background page and do something based on that. 更清楚地说,在脚本中从后台页面获取状态并基于此进行操作。 Previously, I was only injecting the script once the popup was loaded or once initially when the background was initialized. 以前,我只是在加载弹出窗口后或初始化背景时才注入脚本。 Additionally, one must loop through all tabs in all windows to update the state in all tabs (if that's what one wants). 此外,必须在所有窗口中的所有选项卡之间循环,以更新所有选项卡中的状态(如果那是人们想要的)。

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

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