Socket.io in extension


#1

Hi, how can I connect to a socket.io server from an extension (or even from a device)? Is that possible? Which is best?

Thanks in advance, regards!


#2

Hi astoctas,

Yes, you could definitely do this in extension, if you already know how to use socket.io with a normal server. You could use the fetch api in your extension code configuration. But be careful about the CORS issue (Cross-origin resource sharing). You will need to adjust your server to allow request from the mblock ide website.

One more thing: mblock PC does not support sprite extension at this moment. But will do in the new version release in a few months.


#3

Hi, Thanks for the answer.
I’ve tried with a CDN which allow CORS, like this:

onLoad(app, target) {
    fetch('https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js').then(v => {
        v.text().then(txt => {
            eval(txt);
        })
    })
},

but eval not seems to work. It works in another context but from the web ide io object is undefined.

Could you help?
Thanks, regards!


#4

Hi astoctas,

Since you’re loading an external library in this case, it is asynchronous. You may notice that when you console.log the io object, the result of fetch probably hasn’t been returned.

To load the library asynchronously when the extension loaded, there is a way to hack it.

declare a function in the global scope

then call this function in the event handler:

This way, then it will work:

Glad you’re trying this. Hope we could see your extension submitted in the review list soon.

Best,

Allen


#5

Allen,
Excellent! It worked. I can connect to my server.
Iĺl continue trying this extension.

Thank you very much, regards!


#6

My pleasure. Thanks for supporting mBlock :grinning: