E
E
Elvis2020-04-26 16:36:10
JavaScript
Elvis, 2020-04-26 16:36:10

How to fix "io is not defined" error when injecting code?

There is an app for chrome. In it, I add to the page the ability to transfer data to my server using socket.io
On the client side, I do the following:
I implement the library in the head

let sioscript = document.createElement('script');
sioscript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js');
let hh = document.querySelector('head');
hh.appendChild(sioscript);

Next, I implement the connect function and run it from the page
function wsoc(){
    socket = io.connect('http://blablabla.ru/', {path: '/ws/'});
}
let InjectFunction = function(PageScriptSpace, func) {
    PageScriptSpace.innerHTML += func;
}
let RunFunction = function (PageScriptSpace, func_name){
    PageScriptSpace.innerHTML += func_name+'();'
}
PageScriptSpace = document.createElement('script');
InjectFunction(PageScriptSpace, wsoc);
RunFunction(PageScriptSpace, 'wsoc');
h = document.querySelector('head');
h.appendChild(PageScriptSpace);

But when loading the page, it writes an error "io is not defined".
Further, if I write wsoc () in the console, then everything will work.
Why does this error pop up if I initially add the library itself? Moreover, I set a breakpoint on the connection launch line and looked at the page for the presence of the library and it was already there.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SagePtr, 2020-04-26
@Dr_Elvis

After you inject a script tag into the head, do you wait for it to load? Or do you immediately try to work with the variable that is defined in it?

D
Dubolom Unicellular, 2020-04-26
@duboloms

So create an io variable and give it a require or an Import

const io = require("socket.io");
// или
const io = import io from socket.io;

Or whatever you call socket'a function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question