简体   繁体   English

Chrome 扩展:添加内容(启用/禁用图标)

[英]Chrome extension: Add content (enable/disable icon)

I am writing an extension for Google Chrome and I am trying to add content in my current page when the user clicks on the add-on icon.我正在为谷歌浏览器编写一个扩展程序,当用户点击插件图标时,我试图在我的当前页面中添加内容。

I would like to add the possibility to enable/disable the extension and to show/hide my injected content for every page.我想添加启用/禁用扩展和显示/隐藏每个页面的注入内容的可能性。

manifest.json清单文件

"content_scripts": [
  {
    "matches": [
      "http://*/*",
      "https://*/*"
    ],
    "css": ["css/style.css"],
    "js": [
      "js/content.js"
    ]
  }
]

I do not see how to add content only for the page where the icon has clicked because with that, every page has the script.我不知道如何只为点击了图标的页面添加内容,因为这样,每个页面都有脚本。

I also tried something with the background script without success.我也尝试了一些后台脚本,但没有成功。

Do you have any ideas?你有什么想法吗?

Thanks!谢谢!

I had built the same feature for my chrome extension.我为我的 chrome 扩展程序构建了相同的功能。 This will create an on/off switch / toggle (so many names when searching google to solve this :) ) I use the massaging between app and content script in the following method:这将创建一个开/关开关/切换(搜索谷歌时有很多名称来解决这个问题:))我在以下方法中使用应用程序和内容脚本之间的按摩:

manifest清单

inserting my content script on all page (hover.js) and running my extension script (background.js)在所有页面上插入我的内容脚本(hover.js)并运行我的扩展脚本(background.js)

....
"browser_action": {
    "default_icon": {
      "19": "icons/icon-active.png"
    }
  },
"content_scripts": [ 
{ 
  "matches": ["<all_urls>"], 
  "css": ["css/hover.css"], 
  "js": ["js/hover.js"] 
} 
],
"background" : { "scripts": ["js/background.js"] },
....

background.js背景.js

Here we are preparing the background script (which run on all chrome windows) to send and receive extension status在这里,我们正在准备后台脚本(在所有 chrome 窗口上运行)来发送和接收扩展状态

    // start extension as active
var status = true;

// set toggle of extension on browser action click and notify content script
chrome.browserAction.onClicked.addListener(function(tabs) {
  if (status == 'true'){
    status = false;
    chrome.browserAction.setIcon({path: "icons/16x16.png"});
  } 
  else{
    status = true;
    chrome.browserAction.setIcon({path: "icons/icon-active.png"});
  }
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {status: status});
  });
});

// check status on tab update and notify content script
chrome.tabs.onActivated.addListener(function() {
  if (status == 'true'){
    chrome.browserAction.setIcon({path: "icons/icon-active.png"});
  } 
  else{
    chrome.browserAction.setIcon({path: "icons/16x16.png"});
  }
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {status: status});
  });
});

//send extension status on request
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status == "getStatus")
      sendResponse({status: status});
});

As you can see there are 3 functions:如您所见,有3个功能:

  1. change the status on browser action button click.更改浏览器操作按钮单击的状态。

  2. check status when you move to a different tab and notify content script (each tab has it's own "instance" of content script so disabling in one tab might still be active in another tab).当您移动到不同的选项卡并通知内容脚本时检查状态(每个选项卡都有自己的内容脚本“实例”,因此在一个选项卡中禁用可能在另一个选项卡中仍处于活动状态)。

  3. send response of the status on request from content script.根据内容脚本的请求发送状态响应。

content script内容脚本

// check extension status
chrome.runtime.sendMessage({status: "getStatus"}, function(response) {
    if (response.status == 'true'){
        // check elements mouse is hover
        document.addEventListener("mouseover", setLink, true);
    }
    else{
        document.removeEventListener("mouseover", setLink, true);
    }
});

// wait for massage from background script
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.status == 'true'){
        // check elements mouse is hover
        document.addEventListener("mouseover", setLink, true);
    }
    else{
        document.removeEventListener("mouseover", setLink, true);
    }
});

Each content script should first check the status of the extension by sending massage to the background script and recieve a status update.每个内容脚本应首先通过向后台脚本发送消息来检查扩展的状态并接收状态更新。

Also, if we turn the extension off in one tab, when we change tabs we will notify the content script of the change.此外,如果我们在一个选项卡中关闭扩展,当我们更改选项卡时,我们将通知内容脚本更改。

I'm sure that this can be done even better in terms of scripting but i hope it will help...我确信这在脚本方面可以做得更好,但我希望它会有所帮助......

You should be achieve to do this using chrome.tabs.executeScript and chrome.tabs.insertCSS .你应该使用chrome.tabs.executeScriptchrome.tabs.insertCSS来做到这一点。 Full example:完整示例:

Background.js背景.js

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.insertCSS(tab.id, {file: "content_style.css"});
    chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
});

Manifest.json清单文件

{
  "name": "Inject js and CSS",
  "version": "1",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": {
      "16": "icon16.png",
      "19": "icon19.png",
      "32": "icon32.png",
      "38": "icon38.png"
    }
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "permissions": [
    "activeTab"
  ]
}

Edit: Updated to use activeTab, event page and new icon sizes.编辑:更新为使用 activeTab、事件页面和新的图标大小。

What do you think about that?你怎么看?

manifest.json清单文件

{
  "manifest_version": 2,

  "name": "Extension",
  "description": "My extension",
  "version": "0.1",

  "icons": {
    "16": "icons/icon_16.png",
    "48": "icons/icon_48.png",
    "128": "icons/icon_128.png"
  },

  "browser_action": {
    "default_title": "Extension",
    "default_icon": "icons/icon_16_disabled.png"
  },

  "background": {
    "scripts": ["js/background.js"],
    "persistent": true
  },

  "permissions": [
    "activeTab",
    "tabs"
  ]
}

background.js背景.js

var activedTab = {};
var injectedTab = {};

chrome.browserAction.onClicked.addListener(function(tab) {
  if (typeof activedTab[tab.id] === 'undefined') {
    activedTab[tab.id] = true;
    chrome.tabs.insertCSS(tab.id, {file: 'style.css'});
    chrome.tabs.executeScript(tab.id, {file: 'js/content.js'});
    chrome.browserAction.setIcon({path: 'icons/icon_16.png'});
  } else if (activedTab[tab.id]) {
    activedTab[tab.id] = false;
    chrome.browserAction.setIcon({path: 'icons/icon_16_disabled.png'});
    if (injectedTab[tab.id]) {
      chrome.tabs.sendMessage(tab.id, {greeting: 'hide'});
    }
  } else {
    activedTab[tab.id] = true;
    chrome.browserAction.setIcon({path: 'icons/icon_16.png'});
    if (injectedTab[tab.id]) {
      chrome.tabs.sendMessage(tab.id, {greeting: 'show'});
    }
  }
});

chrome.runtime.onMessage.addListener(function(request, sender) {
  switch (request.greeting) {
    case 'content_injected':
      injectedTab[sender.tab.id] = true;
      if (activedTab[sender.tab.id] == false) {
        chrome.tabs.sendMessage(sender.tab.id, {greeting: 'hide'});
      }
      break;
  }
});

chrome.tabs.onUpdated.addListener(function(tabId) {
  delete activedTab[tabId];
  chrome.browserAction.setIcon({path: 'icons/icon_16_disabled.png'});
});

chrome.tabs.onActiveChanged.addListener(function(tabId) {
  if (activedTab[tabId]) {
    chrome.browserAction.setIcon({path: 'icons/icon_16.png'});
  } else {
    chrome.browserAction.setIcon({path: 'icons/icon_16_disabled.png'});
  }
});

content.js内容.js

console.log('loaded');
chrome.extension.sendMessage({greeting: 'content_injected'});

chrome.runtime.onMessage.addListener(function(request) {
  switch (request.greeting) {
    case 'show':
      console.log('show');
      break;
    case 'hide':
      console.log('hide');
      break;
  }
});

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

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