3

I've looked into ES6 modules and require.js but both need a "script" tag on the executing page to be able to use them.

In content scripts we just specify the list of js files to be injected on the webpage and no script tag is used. Is there a module loader i am not aware of that doesn't have dependency on the script tag? Currently i am just using IIFE and global scope to access the required objects but it would be really convenient if i could use a module loader since the size of my extension code is growing day by day.

Note - I am aware of this answer here How to import ES6 modules in content script for Chrome Extension but it suggests to do it via web_accessible_resources but that's not an ideal option cause all scripts injected to page this way have to use message passing to access anything from extension or content script (kind of a workaround).

Praveen Tiwari
  • 1,200
  • 1
  • 12
  • 25
  • 1
    AFAIK modules don't work in content scripts. The only alternative that doesn't use web_accessible_resources or script elements, is quite complicated: chrome.tabs.executeScript in the background page. In short, your implementation of `require()` will post a message to the background, which will call executeScript for this tabId and frameId. The js file should register itself using a global require-like function e.g. register(fn, module, exports), which will then fire an event for which the prior call to require() subscribed so require() will be able to resolve its promise with the loaded module – wOxxOm May 20 '18 at 14:21
  • @wOxxOm got that Thank you, just wanted to make sure there was no straight forward method. – Praveen Tiwari May 20 '18 at 14:32

0 Answers0