0

I am creating an extension that listens to web traffic using a background script, using chrome.webRequest.onBeforeRequest.addListener. However, it only seems to start listening for events once the extension is opened by the user, and it misses everything before.

I thought background scripts were supposed to be running constantly?

relevant code:

background.js

let requests = []

console.log("background script now running");

chrome.webRequest.onBeforeRequest.addListener(function(details){
   requests.concat(details.requestBody)
   console.log(requests.length)
},
{urls: [ "<all_urls>" ]},['requestBody']);

manifest.json

{
  "name": "analytics Extension",
  "description": "Extension to view Analytics Data",
  "version": "0.0.2",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open the popup"
  },
  "permissions": [ "activeTab", "webRequest", "http://*/*", "https://*/*"],
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["./static/js/content.js"],
      "all_frames": true,
      "run_at": "document_end"
    }
  ],
  "web_accessible_resources": ["static/js/script.js"] ,
  "background": {
    "scripts": ["./static/js/background.js"],
    "persistent": true
  } 
}

The more interesting part is that the first print statement I have in the background script prints as soon as I load the extension, but the listener will only start once I open the extension. Please advise

  • The code is fine. Did you look in the [hidden background.js console?](/a/10258029) – wOxxOm Jul 20 '21 at 03:27
  • Yes, that is the console where I see the 'background script now running' statement when the extension is initially loaded – shaunak Jul 20 '21 at 19:43

1 Answers1

0

I ran into this issue as well. In my case, it was because I hadn't declared the host_permissions to include the initiator's domain/path. I noticed you're declaring URLs in permissions. I would put those in host_permissions instead/also.

Josh Levinson
  • 283
  • 3
  • 14