Search code examples
javascripthtmlgoogle-chrome-extensiondom-events

How to run JavaScript Chrome extension even when link clicked and the popup closes


I have some code:

function lic() {
        chrome.storage.local.get('gemam', function(result){
            var num = 2 + parseInt(result.gemam);
            console.log(num);
             chrome.storage.local.set({gemam: num});
        });
        
}
var tt = document.querySelector('#adbox');
tt.addEventListener('click', ()=>{
      lic();
})

Ref is inside of ad which is inside of adbox, like so:

<p id="ad"><!-----ref generated---></p>

the p for ad has a link element() that redirects to another page. Here is an example ref:

<a class='ref' style='color:white!important;' target='_blank' 

I am trying to run code to save data when the link is clicked, but the code cannot run seemingly because I am closing the popup by opening a new tab window.

So in essence, I need to still open the link, and yet run the event listener code even when the popup closes because of the link clicked.


Solution

  • To keep run code after the popup closes you need either a content script or a background script. If you need the code to run across multiple webpages then you have to use a background script if you only want it on one page then you can use a content script.

    Based on what I understand you want to run a function when the link is pressed.

    If the link is on the page:

    You can use a content script to run the function. Because the link has target="_blank" it will open in a new tab and the code will execute.

    If the link is in the popup:

    You need to send a message to the background script telling it to execute the code.