Dynamic Script Installation with Javascript

In short, I'm working on a Google Chrome extension. Extensions do not have access to variables in the area of ​​the page on which they work by default (you need to exchange data through the DOM).

What I'm trying to do is paste the script into the page; this works fine by defining a script tag and src attribute.

The problem is that this script needs a variable that needs to be initialized in advance. To initialize this variable, I am trying to build a script element with its embedded code (and not with an external source), but I am having problems with its operation.

Is this possible, and if so, how to determine the source inside the script? I tried adding node text containing the JS source to the script element, but to no avail.

+3
source share
1 answer

This sucks, but the best way to do this is to possibly communicate your data by entering it in the DOM: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication

You can also accomplish this by doing something like:

var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'alert("It works!");';
document.head.appendChild(script);

I have not tested this, but I assume that it will work from your content scripts.

+1
source

Source: https://habr.com/ru/post/1734195/


All Articles