Fwd: Inject and Run the script to webpage from chrome extension

236 views
Skip to first unread message

Ali Raza

unread,
Oct 19, 2022, 12:50:32 PM10/19/22
to chromium-...@chromium.org, chromium...@chromium.org
Hello team.
We are working on our extension's migration from MV2 to MV3.

In MV2, we were injecting a script in all related webpages as
```
const scriptString = 'function runAtStart () { console.log('our code...'); }';
const script = document.createElement('script'); 
script.textContent = `Our code here.....`
(document.body || document.head || document.documentElement).appendChild(script);
```

According to MV3 policy, we can only inject script tags with src attributes.
```
const s = document.createElement('script');
s.setAttribute('src', 'chrome-extension://<id_of_the_extension>/js/payload.js');
document.documentElement.appendChild(s);
```
Also I have tried this via
*chrome.scripting.registerContentScript*

. and now it is shown to the webpage, but unfortunately it is not calling the methods which I have written into it.
```
await chrome.scripting.registerContentScripts([
{
  id: `tabId-${tab.id}`,
  matches: ['https://*/*'],
  js: ['js/payload.js'],
  runAt: 'document_end',
  world: 'MAIN',
}], (e) => console.log(e));
```

And in the payload.js file, I have just written 
``` console.log("TEST"); ```

In both scenarios, it is adding script tag with src in webpage DOM but not executing it.
Is there anything I am missing.
Below are the screenshots of webpage behaviour.


Screenshot 2022-10-19 at 9.47.22 PM.pngScreenshot 2022-10-19 at 9.47.47 PM.pngScreenshot 2022-10-19 at 9.48.19 PM.png

guest271314

unread,
Nov 5, 2022, 7:44:43 PM11/5/22
to Chromium-discuss, 14bes...@seecs.edu.pk, chromium-...@chromium.org
You can just execute payload.js directly with chrome.scripting.executeScript().

Slade Watkins

unread,
Nov 8, 2022, 9:17:36 PM11/8/22
to guest...@gmail.com, Chromium-discuss, 14bes...@seecs.edu.pk, chromium-...@chromium.org
On Sat, Nov 5, 2022 at 7:45 PM guest271314 <guest...@gmail.com> wrote:
>
> You can just execute payload.js directly with chrome.scripting.executeScript().

Seconding this.

Cheers,
-srw
> --
> --
Reply all
Reply to author
Forward
0 new messages