25

As the questions says, I just want to know the difference between background script and content script in chrome extension. When I logged the chrome object in both the scripts, I found the different objects.

Use case

I want to inject my javascript into the page when the icon is clicked So in manifest.json I added a content script but I am unable to listen to icon click event inside content script.

chrome.browserAction is not defined in chrome object in content script.

Question

How can I listen to click event in content script. Can we include both background and content script ?

This is my manifest.json

{
  "name": "First Plugin Testing",    
  "version": "1.0",
  "manifest_version": 2,    
  "description": "Trying hands on first extension",
  "background": { "scripts": ["background.js"] },
  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "content_scripts": [
    {
      "matches": ["http://*/*"], 
      "js": ["temp.js"]
    }
  ]
}
4

1 回答 1

17

我已经找到了所提问题的答案。

A. 我们可以同时包含内容脚本和背景脚本吗?

的,我们可以在清单中同时包含后台脚本和内容脚本。要在它们之间进行交互,您可以使用Chrome Message Passing API

我也在做同样的事情,但是后台脚本中有一些我看不到的错误,因此我在谷歌上进行了一些搜索后发布了这个问题。

B. 如何在内容脚本中收听点击事件?

解决方案:我们不能browser click event在内容脚本。它只能部分访问 chrome 对象所以你必须在后台脚本中接收点击处理程序并将消息发送到内容脚本并做你想做的任何事情。

在后台脚本中使用chrome.browserAction.onClicked事件,然后使用消息传递将信息发送到用户单击图标的内容脚本。

于 2012-10-18T05:30:11.787 回答