2

I'm trying to access the DOM of the active tab to access some h1 tag for example.

this is what I tried to do:

const contextMenuItem = {
    "id": "roteteimg",
    "title": "rotate img",
    "contexts": ["image"]
};

chrome.contextMenus.create(contextMenuItem);

function func(element) {
    console.log(element);
}

chrome.contextMenus.onClicked.addListener((data, tab) => {
  chrome.tabs.query({active: true}, function(tabs) {
    var tab = tabs[0];
    console.log(tab);

    chrome.tabs.executeScript(tab.id, {
      code: "document.querySelector('h1')"
    }, func);
  });

})

I get the result in func function as an array which populated with one item of an empty object

but when I change code: "document.querySelector('h1')" to code: "document.querySelector('h1').textContent"
I get a string in the array of this header tag value.

How can I get the element itself as the result?
I prefer to have an access to the whole dom of the current tab.

Hope you can help me with that.

zb22
  • 2,390
  • 1
  • 16
  • 28
  • 1
    The approach you're using is correct but it can't transfer DOM elements. You need to perform the work on them inside the injected code. This is explained in what may be a considered an umbrella topic for this kind of problems: [How to access the webpage DOM rather than the extension page DOM?](https://stackoverflow.com/a/4532567) – wOxxOm Jun 26 '20 at 09:47

1 Answers1

0

You can't access the DOM in a background script, you can only interact with it using a content script. If you want to do something specific with the DOM, you need to use the postMessage API to send messages from the content script to the background script (you can even send direct commands from the background script to the content script and back again, so its pretty much the same as interacting with the DOM, except you are doing it through the content script)

wow ow
  • 192
  • 10
  • executeScript used by the OP is already running a content script so this answer is basically a shortened version of [the more informative one](https://stackoverflow.com/a/4532567). If you decided to provide an additional explanation then be specific and address the actual problem directly: DOM elements can't be passed via executeScript or messaging. – wOxxOm Jun 26 '20 at 09:39
  • @wOxxOm my answer preceded the other answerr so ts not a "shortened version" the OPs question has a content script but *does not ahve postMEssage* which is pretty imoprtantay – wow ow Jun 26 '20 at 09:45
  • That answer I've linked is 10 years old so yours didn't precede it. Your answer is a very shortened version of that answer and as such is not really helpful. – wOxxOm Jun 26 '20 at 09:46
  • Also, there's no need for postMessage if the results are being passed back via executeScript's callback, see the documentation and an example in the answer I've linked above. – wOxxOm Jun 26 '20 at 09:48