且构网

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

后台脚本和Chrome扩展中的内容脚本之间的区别

更新时间:2023-12-05 22:45:34

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


A。我们是否可以同时包含内容脚本和后台脚本?


,我们可以同时包含背景脚本和清单中的内容脚本。
要进行交互,您可以使用 Chrome Message Passing API



我也是这样做的,但后台脚本中出现了一些错误,我无法看到,因此我在google上搜索过一些后发布了这个问题。 b
$ b


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

解决方案:我们不能让浏览器单击事件。它只能部分访问铬对象因此,您必须在后台脚本中接收点击处理程序,并将消息发送到内容脚本并执行所需操作。



使用 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.