3

I am looking to import a library into one of my chrome extension's content scripts. Lets take chart.js for instance. I've already looked at this post, but I'm not sure if it is what I need. If it is, then I must be doing something wrong, as I can't seem to get it to work.

I've looked everywhere but I can't seem to find anything regarding the use of libraries in chrome extensions.

Put simply, how can I use and import a javascript library into my chrome extension's content script, so that it can be used in the loaded page?

Thanks, KDJ

What I'm trying now:

chart.js is this file: enter image description here

manifest.json:

enter image description here

In my injected script: enter image description here

Error: enter image description here

chrome.tabs.executeScript() is what spawns the script in which I'm trying to access the library.

KDJ
  • 105
  • 1
  • 2
  • 9
  • 2
    Simply use the [bundle from CDN](https://www.jsdelivr.com/package/npm/chart.js?path=dist) and add it to your `content_scripts` declaration just like any other script. It will add a global variable e.g. `Chart` or whatever. – wOxxOm Feb 04 '21 at 07:28
  • I have tried adding chart.js to content_scripts in the manifest, and then calling "var myChart = new Chart()" from my injected script. However, it is not working, and I just get the reference error "Chart is not defined" when I test it. Am I doing something wrong? – KDJ Feb 04 '21 at 07:37
  • I don't see what you do though so I can only guess you load chart.js in the wrong order (it should be the first) or you use the wrong js file from CDN. – wOxxOm Feb 04 '21 at 07:41
  • I updated the OP with some pictures. Do you see what the problem could be? – KDJ Feb 04 '21 at 07:48
  • I guess you didn't reload the extension or you didn't reload the tab. BTW if you only use chart.js on demand then you don't need to list it in manifest.json - you can load it using executeScript before your main script. – wOxxOm Feb 04 '21 at 08:03
  • I just got it working! I just had to make a few tweaks. Thank you so much for all of your help! I can't believe the solution was so simple. – KDJ Feb 04 '21 at 08:09
  • @KDJ Can you explain how you fixed it? Having a similar issue with a different library. – jimmy Oct 05 '21 at 14:22
  • @NNNComplex This was a long time ago, and I should have left a more detailed solution, but I believe what I did was simply remove the extension from chrome://extensions/ and then add it back again. For some reason either the manifest.json file wasn't being updated or the Chart.js file in the extension files wasn't being added with a normal refresh. – KDJ Oct 06 '21 at 15:12

0 Answers0