How to return a value from script when using chrome.tabs.executeScript

988 views
Skip to first unread message

Ben Bracha

unread,
Aug 21, 2023, 10:50:48 AM8/21/23
to Chromium Extensions
Hi,

I have a simple script file - myScript.js:

(function main() { return 1; })();

I would expect that when running it with chrome.tabs.executeScript (giving it the "file" parameter) that I will receive a result of "1". But I get empty results.

When I run this command on console I get back "1".

Any idea how to return a value from script run by chrome.tabs.exectueScript ?

Thanks

Nihal Titan

unread,
Aug 21, 2023, 11:07:56 AM8/21/23
to Chromium Extensions, Ben Bracha
Here's some logic I'm using to run a function in a tab and get the results (single value).

let myResults = await scriptWait(myTabID,myFunction);

async function scriptWait(target, runfunc)
    {
    return new Promise((resolve, reject) =>
        {
        try
            {
            if(!target?.tabId) { resolve(); }
            chrome.scripting.executeScript(
                {
                target : target,
                func : runfunc
                },
            function (result)
                {
                if(result)
                    {
                    resolve(result[0].result);
                    }
                resolve();
                });
            }
        catch {resolve();}
       
        });
    }

Ben Bracha

unread,
Aug 21, 2023, 11:09:37 AM8/21/23
to Nihal Titan, Chromium Extensions
You are using the chrome.scripting api which is from v3
I’m using v2 and other api 

Ben Bracha

unread,
Aug 21, 2023, 12:30:38 PM8/21/23
to Nihal Titan, Chromium Extensions
It seems to work if I use a simple script. But if my script is a webpack module, it doesn't work - no return value.
Does anyone have experience with this?

wOxxOm

unread,
Aug 22, 2023, 2:19:11 AM8/22/23
to Chromium Extensions, Ben Bracha, Chromium Extensions, Nihal Titan
You can use webpack's DefinePlugin to add a footer like `;window.result` so that it becomes the last code in the output file and in your own code you'll set it like window.result = 'foo'
Note that this works only for synchronous code, so if you use Promise or any other asynchronously running code you'll need to use chrome messaging to send the result.

wOxxOm

unread,
Aug 22, 2023, 2:21:06 AM8/22/23
to Chromium Extensions, wOxxOm, Ben Bracha, Chromium Extensions, Nihal Titan
Oops, not DefinePlugin but wrapper-webpack-plugin or a similar one.

Ben Bracha

unread,
Aug 24, 2023, 9:25:58 AM8/24/23
to wOxxOm, Chromium Extensions, Nihal Titan
That seem to work well

Thank you very much 
Reply all
Reply to author
Forward
0 new messages