Is there a way to access the current tab dom?

Viewed 55

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.

1 Answers

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)

Related