sundowatch
sundowatch

Reputation: 3093

Chrome Extension run the process on spesific tab

I'm trying to run some scripts on the spesific tab which is assigned on the page of extension's button clicked.

For example, if I click the button which is on the popup.html, it should only run on this page to the end of the script even if I switch to another tab.

My algorithm is like that:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  //Some other processes
  chrome.tabs.getSelected(null,function(tabS) {
    //Some other processes
    chrome.tabs.executeScript(null, {file:"some_js.js"});
  });
});

I'm using some DOM operations on the page. If I switch to another tab, the process is interrupted, because it listens the current tab. I want to assign an id to the process tab and make this codes work on this tab. How can I do it?

Upvotes: 2

Views: 2359

Answers (1)

herodrigues
herodrigues

Reputation: 967

Add a button element in popup.html. Then add this code to popup.js:

function handleClick (e) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.executeScript(tabs[0].id,
        { code: `setInterval(function () { console.log('This event is running only at the tab with domain: ${tabs[0].url} after 1000ms') }, 1000)` })
  })
}

document.addEventListener('DOMContentLoaded', function () {
  const button = document.getElementById('popup-button')
  button.addEventListener('click', handleClick)
});

When you click the button, that code will be executed only in that specific tab. You'll be able to see that message in the developer console.

The code can also be another JS file that you have in your extension. Just like you did it in your question.

Obs: chrome.tabs.query is not really necessary here as if you execute chrome.tabs.executeScript passing null as parameter, it already gets the active tab in the current window. I also added the tabs permission in order to get the tabs[0].url attribute. Anyway, this way you have more control of what tab you're manipulating as you get their tabId and url attributes.

Upvotes: 2

Related Questions