How to get remote javascript file in Chrome Extension

I've read all the threads I could find on stackoverflow and google but still can't get this to work.

What I need is to keep my JS code in a script on the server, so I don't have to re-publish the extension every time I decide to make a change. Users also won't have to update their extensions.

Methods that don't work due to the new security policy :

  • Insert script by adding tag to
  • Source Eval () script after receiving request from ajax.

As google says there is some method to download remote script download.

Relaxing security policy for remote scripts

Here's what they say:

A lightweight policy definition that allows script resources to be loaded from example.com over HTTPS looks like this:

"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 am trying to load this script into 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 check if the objects declared in the remote file are available. And they are not available ... I'm not even sure if the remote script was loaded ...

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

How to make remote javascript functions available in background.js?

+3


source to share


1 answer


It works for me in extension workflowyCodeFormatter . Yours manifest.json

is ok, what you need to do is add 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 to access JavaScript in my JS files, ironically the browser thinks I don't have them, even though doing everything works fine. To get around the browser spitting out console errors, I wrapped all my calls in the JS I need in try / catch blocks. Let's say you wanted to call fireWebSockets()

from yours extension-script.js

, you should do something like this:



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

      

Hope it helps!

+1


source







All Articles