Search code examples
javascriptgoogle-chrome-extensiongoogle-chrome-devtools

Getting active tab and generating confirm window


I'm trying to develop extension that gets active tab and generate confirm window at current open tab. But I cannot do this with "window.confirm" because window is not defined. Here's my code:

BACKGROUND.JS

var notifyTimer = setInterval(func,5*1000);
  console.log('setinterval ran');

  
  function func(){ 
  let ActiveTab = getCurrentTab();
  console.log(ActiveTab)

}

async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  console.log(tab.url)
  //alert(" Hello!")
  // SOME CODE TO GENERATE CONFIRM WINDOW or ALERT
  return tab;
}

Currently it's fetching current active tab but I don't know how to generate confirm window

Kindly help me to generate alert with this code.


Solution

  • Is this what you want to do?

    enter image description here



    manifest.json

    {
      "name": "hoge",
      "version": "1.0",
      "manifest_version": 3,
      "permissions": [
        "scripting"
      ],
      "host_permissions":[
        "<all_urls>"
      ],
      "background": {
        "service_worker": "background.js"
      }
    }
    

    background.js

    var notifyTimer = setInterval(func, 5 * 1000);
    console.log('setinterval ran');
    
    
    function func() {
      let ActiveTab = getCurrentTab();
      console.log(ActiveTab)
    
    }
    
    const alert = () => {
      alert(" Hello!");
    }
    
    async function getCurrentTab() {
      let queryOptions = { active: true, lastFocusedWindow: true };
      let [tab] = await chrome.tabs.query(queryOptions);
      console.log(tab.url)
      //alert(" Hello!")
      // SOME CODE TO GENERATE CONFIRM WINDOW or ALERT
      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: alert
      });
    
      return tab;
    }