Synchronous execution of inline javascript in manifest v3

324 views
Skip to first unread message

Vinod Kumar

unread,
Dec 14, 2023, 2:29:08 AM12/14/23
to Chromium Extensions
Hi,

 In manifest v2 inline javascript can be injected and executed synchronously by using a document.append(<script element>). But in manifest v3 due to CSP restrictions, an inline script can be injected by only using asynchronous scripting API. 

We have a use case of executing an inline script on the click action of an HTML element and need to wait for the inline script execution to complete before updating the UI. 
However, due to the asynchronous nature of scripting API, the code that updates UI is not getting blocked until inline script execution. We don't have control of UI updating code. It is inside a web page.

Ex:- HTML link with the text "Open", on click action text will be updated to "Close". Before text updation, the inline script has to run.

Please let me know if there is a way to make inline script execution synchronous.

Regards,
Vinod.



wOxxOm

unread,
Dec 14, 2023, 6:23:52 AM12/14/23
to Chromium Extensions, Vinod Kumar
The workaround is to always run that script in MAIN world (either in manifest.json or using chrome.scripting.registerContentScripts) so that it runs whenever this site loads. The actual logic will be inside addEventListener('foo', () => {......}) where foo is a unique event name and then your normal content script will use the synchronous dispatchEvent(new Event('foo')) when necessary.

It's unclear though why you need to run the code in MAIN world and not as a normal content script.

Vinod Kumar

unread,
Dec 18, 2023, 12:35:06 PM12/18/23
to Chromium Extensions, wOxxOm, Vinod Kumar
Thanks,

It's unclear though why you need to run the code in MAIN world and not as a normal content script.
 --> We need to call the JS function of main page from inline script.

Found your answer from stack overflow. I will use the methods mentioned here.

Oliver Dunk

unread,
Jan 3, 2024, 6:14:44 AM1/3/24
to Chromium Extensions, uppu.vi...@gmail.com, wOxxOm
In this specific case, I think there are hopefully some ways to workaround the lack of synchronous script execution (you should still be able to delay updating the text).

We did also discuss having something like a `chrome.dom.executeScript` method in the Web Extensions Community Group, though we haven't finalized that and weren't ready to commit to it being synchronous. See "Synchronous execution in main world from content script" here.

Reply all
Reply to author
Forward
0 new messages