0

I am making a Google Chrome extension and I am trying to use the .click() function within one of my script. The click function should click a link which redirects me to another page. Once I have been redirected, I would like to send a chrome.runtime message.

document.getElementsByClassName('example-link')[1].click(function() {
       console.log("Hello World");
        let data = {
            type: "example"
        }
        chrome.runtime.sendMessage({...data}); 

    });

So far the page redirects, but the console.log() doesn't show and the runtime message doesn't send. I am not sure whether I have misunderstood the purpose of the callback function or whether the scripts stops running because I am on a new page.

Any explanation / help would be appreciated.

HarryShotta
  • 347
  • 1
  • 15
  • Problem here is the fact you want to send a message on the next page load. click() does not have a callback. – epascarello Feb 14 '20 at 14:20
  • So on a new page load, this script gets loaded again from fresh and so the callback in never called? Or does the .click() function not have a callback at all?How might I solve this? – HarryShotta Feb 14 '20 at 14:23
  • 1
    click has no callback, it just triggers the action. Somehow you need to call it on the next page load. I am not a big chrome extension developer so I really can not help. Going to be something with load or update in the tab. – epascarello Feb 14 '20 at 14:24

1 Answers1

1

click() doesn't take a callback.

In order to detect navigation you need:

  1. to listen for an onUpdated event (see How to listen for url change with Chrome Extension.)
  2. then click() to trigger the navigation
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I ended up listening for the change in my background script: chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { if(tab.url !== undefined && changeInfo.status == "complete"){ } }) – HarryShotta Feb 14 '20 at 14:41