最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Manifest V3 extension, accessing local functions - Stack Overflow

programmeradmin3浏览0评论

What I would like to do

I'm trying to create a small extension for my own usage. For this extension to work I need to execute a "local" js function call on a web page (that I do not own) and pass the result to my background service worker script. So far I was either able to:

  • Have a content_scripts be able to execute the "local" function (using "world": "MAIN"), but this script can't access chrome.runtime.sendMessage().

Uncaught (in promise) Error: Extension context invalidated. or

  • Have the content_scripts successfully send message to my background service worker but is not able to access the "local" function

main.js:4 Uncaught (in promise) ReferenceError: myFuncName is not defined

How do I do that?

What I tried

  • In the following files, if I let them as is, I get a ReferenceError on the 4th line of main.js.
  • If I comment this line an uncomment the 5th line it works (but is not what I want)
  • If I add "world": "MAIN" in the "content_scripts" section of the manifest.json, I get the Extension context invalidated on line 7 of main.js

manifest.json

{
  "manifest_version": 3,
  "name": "ExtName",
  "version": "0.0.1",
  "content_scripts": [
    {
      "matches": ["*://url/*"],
      "js": ["main.js"]
    }
  ],
  "host_permissions": [
        "*://*/*"
    ],
  "background": {
    "service_worker": "background.js"
  }
}

main.js

var intervalID = window.setInterval(checkValue, 1000);

function checkValue() {
    let value = getValue();
    // let value = "value";
    if (value) {
        const response = await chrome.runtime.sendMessage({status: value});
        console.log(response.text);
    }
};

background.js

function handleMessage(request, sender, sendResponse) {
    console.log(request.status);
    sendResponse({ text: "Received!" });
}

chrome.runtime.onMessage.addListener(handleMessage);

in the page script (that I do not control)

function getValue() {
    return "value";
}
发布评论

评论列表(0)

  1. 暂无评论