4

for some reason my executeScript function is not working. This is my code:

async function scrape_get_url(){
    console.log("Getting url: " + from_url);
    var tab_id;
    chrome.tabs.create({ "url": from_url}, function(newTab){
        tab_id = newTab.id;
        console.log("Checking for tab url update");
    });
    chrome.tabs.onUpdated.addListener( function(tabId, info) {
        if(tabId == tab_id && info.url){
            console.log("Executing scrape script");
            console.log("tab id:" + tab_id);
            console.log("updated tab url:" + info.url);
            chrome.scripting.executeScript({
                target: {tabId: tab_id},
                function: scrape
            });
        }
    });
}
function scrape(){
    console.log("Getting Element...");
}

This is my output:

Getting url: https://developer.chrome.com/docs/extensions/mv3/getstarted
Checking for tab url update
Executing scrape script
tab id:293
updated tab url:https://developer.chrome.com/docs/extensions/mv3/getstarted/

I have an onUpdated listener due to a chrome bug, as stated here. Also, the reason I put the onUpdated function outside of the create function's callback, is because according to another question on StackOverflow(that I can't find anymore :/ ), putting the executeScript within the create's callback will not run the script.

My permissions are set correctly in the manifest file.

JorensM
  • 330
  • 4
  • 15
  • 4
    The code is fine. Your mistake is probably that you look in the wrong console. The executed script runs in the web page so you need to look in its devtools. – wOxxOm Dec 18 '21 at 10:04
  • @wOxxOm Hey, you were right! My bad... Thanks a ton!!! – JorensM Dec 18 '21 at 18:21

1 Answers1

0

I saw the chromium bug report, and I dug deep into this.

I don't have a solution, I have a hack that works.

function _func(res){
    setTimeout( () => {
    // Do things with the page.
    }, 3000);
}
chrome.tabs.create({url: 'https://www.example.com'}).then((tab) => {
        setTimeout(() => {
            chrome.scripting.executeScript({
                target: {tabId: tab.id},
                func: _func //,
                // I used args in my case, you dont have to. args: [msg.content]
            })
        }, 3000)
    });
A. Abramov
  • 1,823
  • 17
  • 45
  • My problem was that I was looking into the wrong console. The executed script runs in its own window and you have to look into that window's console. – JorensM Mar 14 '23 at 09:11