Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a button on chrome extension DOM(popup.html) is clicked, extension DOM is closed and onclick function is not called in popup.js

I am writing a chrome extension to record the requests fired once I click on start button.

Here are my files: 1. manifest.json

{
  "manifest_version": 2,

  "name": "recorder",
  "description": "Recorder",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "storage",
    "webRequest",
    "<all_urls>",
    "webRequestBlocking",
    "background"
  ],

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

}
  1. popup.html

    Here 2 buttons are created with id as "record" and "stop"

  2. popup.js

    document.getElementById("record").addEventListener("click", startRecording);
    document.getElementById("stop").addEventListener("click", stopRecording);
    
    function startRecording() {
         var RequestFilter = {};
         var  MatchPatterns = ['http://*/*', 'https://*/*'];
    
         RequestFilter.urls = MatchPatterns;
    
            RequestFilter.types = ['main_frame', 'sub_frame', 'object', 'xmlhttprequest', 'stylesheet', 'script' , 'image'];
            chrome.webRequest.onSendHeaders.addListener(onSendHeaders, RequestFilter,
            ['requestHeaders']);
    }
    
    
    function stopRecording() {
        chrome.webRequest.onSendHeaders.removeListener(onSendHeaders);
    }
    
    function onSendHeaders(info) {
          console.log(info.url);
    }
    

Now when I open the extension in chrome, a DOM opens up with 2 buttons on it. When I click the button with id as "record", extension DOM(popup.html) gets closed and nothing happens.

But when I right click and inspect the popup and then click on "record" button, popup.html remains open and URLs are printed on console.

expected behaviour is: When record button is clicked, extension should get minimised but the function called on button click should work until stop button is clicked.

like image 271
Ranu Sisodia Avatar asked Nov 30 '25 07:11

Ranu Sisodia


1 Answers

I am able to do this using passing request between popup.js and background.js

I have used chrome.extension.sendRequest to send a Param type: 'start' in popup.js

In background.js I have added a listener onRequest that listen to the request sent.

This way I was able to record in background.

like image 176
Ranu Sisodia Avatar answered Dec 01 '25 20:12

Ranu Sisodia