Chrome Extension - Passing object from page to context script

前端 未结 2 1222
臣服心动
臣服心动 2020-11-27 23:50

I\'m writing a chrome extension and I\'m struggling to pass an object back from the main page to the context script. I can\'t seem to access the window\'s variables.

2条回答
  •  离开以前
    2020-11-28 00:09

    Above answer may work but I don't think it is the correct way ...

    First:

    If you already published your extension, get the application key and put it into your manifest "key" as described here:

    • install Chrome Extension Source Viewer
    • CRX -> view extension source -> enter published application URL -> enter
    • open developer tools (F12) -> go to console
    • copy the "key" atring from the console into your local manifest.json:

      "key": "MIIBIjANBgkqhkiG9w...RwIDAQAB",

    This will ensure your local and published extension have the same extensionId

    Second:

    • load your local extension
    • find out your extensionId by going to chrome://extensions and looking for ID under your extension title

    Third:

    in your background script (ie background.js) listen for msgs like this:

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
       if (message.name === 'msg1') {
          alert(message.key1);
       }
    });
    

    in your content script (ie contentScript.js) send msgs like this:

    chrome.runtime.sendMessage(extensionId, { name: 'msg1', key1: 'value1'}, undefined, (response) => {});
    

    (replace extensionId with the one you got in the second step)

提交回复
热议问题