Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

chrome.runtime is undefined in main world

84 views
Skip to first unread message

Bala Abhinav

unread,
Dec 9, 2024, 11:57:21 PM12/9/24
to Chromium Extensions
Hi,

I have recently added another content script to my extension which needs to run in the MAIN world for the functionality i intend to build. I am using crxjs/vite-plugin to bundle the project and crxjs typically creates a loader file where It loads the content script using chrome.runtime.getURL API.

In this case, an error is being thrown stating the following : 
TypeError: Cannot read properties of undefined (reading 'getURL')

So, I would like to understand whether chrome.runtime is not accessible to scripts loaded in the MAIN world?
For additional context, the script is loaded statically through the manifest file. The alternative solution I am considering is to inject script manually through the chrome.scripting API. Any help regarding this would be much appreciated.

Thanks,
Bala

woxxom

unread,
Dec 10, 2024, 5:26:01 AM12/10/24
to Chromium Extensions, Bala Abhinav
This is because the script is no longer a part of the safe isolated world, but just a conventional web page script that runs in the same JS environment as any other web page scripts, so it doesn't have any extension-specific API.

Your main world script can use messaging so that the recipient will call the required chrome API on behalf of your script (like chrome.scripting.executeScript) and optionally send the result back:
Note that the MAIN world is unsafe as the page may redefine a built-in prototype or a global and exfiltrate data from your private communication or make your injected code fail. Guarding against this is complicated (see Tampermonkey's or Violentmonkey's "vault"), so make sure to verify all the received data.

Reply all
Reply to author
Forward
0 new messages