Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current active tab from a new pop up window created by chrome.windows

I am going to create a chrome extension that will pop up a new window, by doing this

chrome.windows.create({
  url: chrome.runtime.getURL("popup.html"),
  type: "popup",
});

my problem is from "pop up window" I want to access the active Tab from the "main window", for example I want to change the background of the DOM from the active tab from where I clicked the extension that shows the popup window. I hope the question is not confusing. :)

manifest.json

{
 "name": "test",
 "description": "test",
 "version": "1.0.0",
 "manifest_version": 3,
 "background": {
   "service_worker": "background.js"
 },
 "permissions": ["storage", "activeTab", "scripting", "tabs"],
 "action": {
   "default_icon": {
     "16": "Icon-16.png",
     "32": "Icon-32.png",
     "48": "Icon-48.png",
     "128": "Icon-128.png"
    }
 },
"icons": {
   "16": "Icon-16.png",
   "32": "Icon-32.png",
   "48": "Icon-48.png",
   "128": "Icon-128.png"
 }
}

on the pop up window, i have this onclick function

const onClick = async (e) => {
if (e && e.preventDefault) e.preventDefault();


const [tab] = await chrome.tabs.query({
  active: true,
  currentWindow: true,
});

chrome.scripting.executeScript({
  target: { tabId: tab.id },
  function: () => {
    chrome.storage.sync.get("color", ({ color }) => {
      document.body.style.backgroundColor = color;
    });
  },
});

};

like image 838
Marcus Jason Avatar asked Oct 18 '25 07:10

Marcus Jason


1 Answers

Get the active tab before creating the window and pass the id as a URL parameter.

extension script:

async function openPopup() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.windows.create({
    url: `popup.html?${new URLSearchParams({
      tabId: tab.id,
    })}` ,
    type: 'popup',
  });
}

popup.html:

<script src="popup.js"></script>

popup.js:

const activeTabId = Number(new URLSearchParams(location.search).get('tabId'));
chrome.scripting.executeScript({ target: { tabId: activeTabId }, function: foo });
function foo() {
  console.log('injected foo');
}
like image 170
wOxxOm Avatar answered Oct 20 '25 21:10

wOxxOm