且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

chrome扩展中后台脚本和内容脚本的区别

更新时间:2023-12-05 09:04:46

我已找到问题的答案.

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

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

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

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

解决方案:我们不能在内容脚本中有浏览器点击事件.它只能部分访问 chrome 对象,因此您必须在后台脚本中接收点击处理程序并将消息发送到内容脚本并执行您想做的任何操作.

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

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"]
    }
  ]
}

I have found the answer to the questions asked.

A. Can we include both content script and background script ?

Yes, we can include both the background scripts and content scripts in manifest. To do interaction between them you can use Chrome Message Passing API.

I was doing the same way but there was some error in background script which I could not see therefore I posted this question after some searching on google.

B. How can I listen to click event in content script ?

Solution: We can not have browser click event in content script. It has only partial access to chrome object So you have to receive the click handler in background script and send message to content script and do whatever you want.

Use chrome.browserAction.onClicked event in background script and then use message passing to send the information to content script that user clicked on icon.