Pull to refresh
7
0
Даниил @TsDaniil

javascript разработчик

Send message

Web Worker easier than you thought

Reading time6 min
Views3.7K

Web Worker easier than you thought


In this article, a DIRTY, unsafe, unstable and scary <em>eval</em> method will be described. So, if you are uncomfortable with that, stop reading right now.


First off, some issues with convenience remained unresolved: in code sent to web web workers, closure can't be used.




All of us like new technologies, and all of us like new technologies to be convenient to use. However, it's not exactly the case with web workers. web workers accept files or links to files, which isn't convenient. It would be good to be able to put any task into web workers, not just specifically planned code.


What do we need to make web workers more convenient to operate? I believe, it's the following:


  • A possibility to launch in web workers any code at any moment
  • A possibility to send to web workers complicated data (class instances, functions)
  • A possibility to receive a promise with a reply from a web worker.
Read more →
Total votes 6: ↑6 and ↓0+6
Comments0

Работа с Worker “как хочется“, а не “как можно”

Reading time6 min
Views6.3K

В этой статье будет использоваться ГРЯЗНЫЙ, небезопасный, "костыльный", страшный и т. д. метод eval. Слабонервным не читать!


Сразу скажу, что некоторые проблемы удобства использования решить не удалось: в коде, который будет передан в worker, нельзя использовать замыкание.
Работа с Worker "как хочется", а не "как можно"

Читать дальше →
Total votes 25: ↑22 and ↓3+19
Comments15

Protocol for communication between iframe and the main window

Reading time4 min
Views4.9K

From time to time, developers need to establish communication between several browser tabs to be able to send messages from one tab to another and receive responses. We have also faced this need at some point.


Some solutions already exist (like, for instance, BroadcastChannel API). However, its browser support leaves a lot to be desired, so we decided to use our own library. When the library was ready, that functionality was no longer required. Nevertheless, another task emerged: communication between an iframe and the main window.


On closer examination, it turned out that two-thirds of the library would not have to be changed — only some code refactoring was necessary. The library is a communication PROTOCOL that can work with text data. It can be applied in all cases in which text is transferred, such as iframes, window.open, worker, browser tabs or WebSocket.


How it works


Currently, the protocol has two functions: sending messages and subscription to events. Any message in the protocol is a data object. For us, the main field in that object is type, which tells us what kind of message it is. The type field is an enum with the following values:

Read more →
Total votes 13: ↑12 and ↓1+11
Comments2

Протокол для общения между iframe и основным окном браузера

Reading time4 min
Views7.9K

Многим разработчикам периодически требуется наладить общение между несколькими вкладками браузера: возможность посылать сообщения из одной в другую и получать ответ. Такая задача встала и перед нами.


Существуют стандартные решения вроде BroadcastChannel, однако поддержка в браузерах сейчас оставляет желать лучшего, поэтому мы решили реализовать свою библиотеку. Когда библиотека была готова, выяснилось, что такая функциональность уже не нужна, зато появилась другая задача: нужно было общаться между iframe и основным окном.


При ближайшем рассмотрении выяснилось, что две трети библиотеки при этом можно не менять, необходимо только немного порефакторить код. Библиотека представляет из себя скорей ПРОТОКОЛ общения, который может работать с текстовыми данными. Его можно применять во всех случаях, если есть возможность передавать текст (iframe, window.open, worker, вкладки браузера, WebSocket).


Как это работает


На данный момент в протоколе есть две функциональности: отправка сообщения и подписка на события. Любое сообщение в протоколе — это объект с данными. Главное поле этого объекта — поле type, которое говорит нам, что это за сообщение. Поле type — это enum со значениями:

Читать дальше →
Total votes 21: ↑20 and ↓1+19
Comments8

Information

Rating
Does not participate
Location
Москва, Москва и Московская обл., Россия
Date of birth
Registered
Activity