简体   繁体   中英

How to get remote javascript file in Chrome Extension

I've read all topics I could find in stackoverflow and google, but still can't get this to work.

What I need - is to save my JS code in script on server, so I would not need to republish extension every time I decide to make changes. And users wouldn't have to upgrade their extensions also.

Methods that do not work due to new Security Policy :

  • Inject script via adding tag to
  • Eval() script source after receiving it from ajax request.

As google says, there is some method to imlement remote script loading.

Relaxing Security Policy for remote scripts

Here is what they say:

A relaxed policy definition which allows script resources to be loaded from example.com over HTTPS might look like:

 "content_security_policy": "script-src 'self' https://example.com; object-src 'self'" 

Ok, I did what they said in my manifest.json:

"content_security_policy": "script-src 'self' https://beta.tradernet.ru; object-src 'self'"

And I try to load that script in my background.html

<head>
<title>My Awesome Backgound page!</title>
<script src="https://beta.tradernet.ru/js/extension-script.js"></script>
<script src="background.js"></script>
</head>

In my background.js I test if objects, declared in remote file are available. And they are not available ....I'm not even sure that remote script was loaded...

If I add similar tag to my popup.html, then it works and functions loaded from remote script are available...

How do I make remote javascript functions available in background.js?

I've got it working in my workflowyCodeFormatter extension. Your manifest.json is fine, what you need to do now is inject that script using JavaScript, something like this should do it:

(function () {
  'use strict';
  var scriptToLoad = document.createElement('script');
  scriptToLoad.type = 'text/javascript';
  scriptToLoad.async = true;
  scriptToLoad.src = 'https://beta.tradernet.ru/js/extension-script.js';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(scriptToLoad, s);
}());

This allows me access to the JavaScript in my JS files, ironically though, the browser thinks I don't have them, even though executing everything works perfectly. To get around the browser spitting out console errors, I wrapped all my calls to the JS I needed in try/catch blocks. Let's say you wanted to call fireWebSockets() from your extension-script.js , you should do something like this:

(function () {
  'use strict';
  window.addEventListener('load', function () {
    try {
      fireWebSockets(foo);
    } catch (ignore) {}
  });
}());

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM