Paschalis
Paschalis

Reputation: 12301

Change a tab's DOM from Event Page

I have an Event Page, in which I set some listeners to find out when user changed the URL in the current tab, using:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    myFunction(tab);
});

Now, I want to change some parts of the tab's DOM, in using myFunction. I have tested it a bit, and it seems that the DOM I am currently changing, it's not the same as the tab's, that user has changed.

I 'm kinda new on this, and I don't know if I have to use Content Scripts.

Thanks!

Upvotes: 0

Views: 237

Answers (1)

Bjorn
Bjorn

Reputation: 71930

If you are asking how to change the tab's DOM, I would use a content script for that. Then use postMessage to communicate between your event page and your content script if you need to, but event pages can disappear, so that may not be a reliable channel.

This is from the Google Code documentation:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null,
                           {code:"document.body.bgColor='red'"});
});

If you are asking how to get the current tab, getting the current tab can vary depending on the context. Below is what has worked for me recently.

In the popup.html for a browser action I have:

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      var current;
      if (_.isEmpty(tabs)) {
        return;
      }
      current = tabs[0];
   });

And in a chrome-extention:// I use:

   chrome.tabs.getCurrent(function(tab) {
   });

Upvotes: 2

Related Questions