-1

I want to create a new tab and modify the DOM inside a Chrome Extension's background.js with manifest V3:

  chrome.tabs.create({ url : 'http://example.com'},function(newTab) {
    document.body.innerHTML = "Example.com website content modified in tab "+ newTab.id + "!";
  }

But why is this not doing anything, and how to fix this?

This below also didn't work:

  chrome.tabs.create({ url : 'http://example.com'},function(newTab) {
    function myScript(){
            document.body.innerHTML = "Example.com website content modified in tab "+ newTab.id + "!";
    }

    chrome.scripting.executeScript( {
                    target: {tabId: newTab.id},
                    function: myScript,
    });
  }
notabeen
  • 1
  • 2

1 Answers1

0

background.js doesn't have access to the dom of a page, you'll have to run content script and use messaging to communicate between background and content scripts.

vanowm
  • 9,466
  • 2
  • 21
  • 37
  • How would you use messaging? Can do an `eval()` for everything that's passed from background.js to content-script.js? – notabeen Jun 29 '21 at 22:02
  • That would be a one way to do it, very inadvisable though. A better solution is to move whatever dom manipulation code you planned using in background.js into the content script and background would simply send commands to content script. – vanowm Jun 29 '21 at 22:18