0

I am creating a Firefox extension, where I want to get the stack trace each time a network request is sent. Currently, I inject a content script to access the stack but cannot get the content script to send the stack trace back to background script. Specifically, I listen for a message in content script (from background script) with browser.runtime.onMessage.addListener and call my code in the content script to get me the stack trace but it seems that when I am inside the browser.runtime.onMessage.addListener I cannot call JS methods that I injected with the content script. Any ideas on how I can get the stack trace when a network request is initiated?

background.js:

browser.webRequest.onBeforeSendHeaders.addListener(
    function (details) {
        if (details.tabId == -1) {
            return;
        }

        browser.tabs.sendMessage(details.tabId, { content: details.url });

    },
    {
        urls: [
            "http://*/*",
            "https://*/*",
        ],
    },
    ["requestHeaders", "blocking"]
);

content_script.js

function getPageScript() {
    return "function codeToInject() {console.trace();} codeToInject();";

}
  
function insertScript(text) {
    var parent = document.documentElement,
      script = document.createElement('script');
    script.text = text;
    script.async = false;

    parent.insertBefore(script, parent.firstChild);
}

browser.runtime.onMessage.addListener(returnStack);

function returnStack() {
    insertScript(getPageScript());
}

manifest.json

{
    "manifest_version": 2,
    "name": "call-stack-retrieval",
    "version": "0.0",
    "background": {
        "persistent": true,
        "scripts": [
            "background.js"
        ]
    },
    "content_scripts": [{
        "all_frames": true,
        "js": [
            "content_script.js"
        ], 
        "match_about_blank": false, 
        "matches": [
          "<all_urls>"
        ], 
        "run_at": "document_start"
    }],
    "permissions": [
        "tabs", 
        "<all_urls>", 
        "contextMenus", 
        "webRequest", 
        "webRequestBlocking", 
        "webNavigation", 
        "storage", 
        "unlimitedStorage", 
        "notifications"
    ]
}
Umar Iqbal
  • 669
  • 1
  • 11
  • 31
  • So you want the stack trace from the content script to be passed on to the background script? – Rojo Mar 25 '21 at 15:33
  • The script you inserted from the content script is not a content script anymore, it's just a page script. To communicate with the page script you can use DOM messaging via CustomEvent, see this [example](https://stackoverflow.com/a/19312198) and [another example](https://stackoverflow.com/a/46870005) of a full communication chain. – wOxxOm Mar 25 '21 at 15:34
  • @Rojo yes, that is the intent. – Umar Iqbal Mar 25 '21 at 15:35
  • Consider using [ports](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port) – Rojo Mar 25 '21 at 15:35

0 Answers0