otictac1
otictac1

Reputation: 205

Chrome Extension Manifest V3 chrome.scripting.executeScript only works first time

I am writing a Chrome Extension that takes data from a webpage and displays it in a new tab. It works great the first time you click the icon button, but the second time the icon is clicked, it creates the new tab, but the data isn't refreshed. If I reload the extension it works again for the first time.

manifest.json

{
    "name": "Log Missing Copy",
    "version": "3.7",
    "manifest_version": 3,
    "action": {},
    "permissions": ["activeTab", "scripting", "tabs", "storage"],
    "background": {
      "service_worker": "background.js"
    }
  }

content.js

console.log('here');

let oTable = document.getElementsByClassName('grid-table')[1].children[2]
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))
chrome.storage.local.set({"targetList": data});

background.js

chrome.action.onClicked.addListener((tab) => {

    chrome.scripting.executeScript({
        target: {tabId: tab.id},
        files: ['content.js']
      });

    chrome.tabs.create({'url':'copy.html'});
    
  });

Upvotes: 1

Views: 3165

Answers (2)

Narek
Narek

Reputation: 1

You can also wrap it in IIFE (Immediately Invoked Function Expression) like this:

(function (){
  *... write your code*
})()

You can also use this approach for async tasks eg.:

(async function (){

   await someData

})()

Upvotes: 0

otictac1
otictac1

Reputation: 205

I figured this out. It was calling it every time, but it was failing because it said that content.js was reinitializing a variable. I changed it to var and it started worked.

Upvotes: 1

Related Questions