Local Storage Bridge(LSBridge)web一機多屏通信

The problem

What is this all about? I’m working on a single page application that may be placed inside an iFrame. If you ever did that you probably know that working in such scenario is not the easiest thing on the planet. For example, we see the HTTP requests in the browser’s console but we can’t log anything (edit: we can). My first idea was to use the solution in that context. However, after posting this article to reddit I found out that there is another simpler workaround. Still, such type of communication may be useful if we want to exchange data between two (or more) tabs in a same browser.

For a short period of time I was thinking about things like reading location hash value or attaching methods to the iFrame’s window object. Then I remembered about earhorn library. It’s a piece of code that logs JavaScript executions. Really helpful but I’m not going into that now. It’s interesting how this tool produces its output. Shortly:

We pass our source to earhorn and we get the same code but instrumented.
In a new tab of the browser we load a page provided by the library.
Then, with the same browser, we open our application containing the instrumented code and start using the app.
If we go to the newly opened tab we’ll see that our actions are logged.
How is this possible? Our application is not making HTTP request and it’s not wired to a socket server. It looks like the two tabs are communicating somehow.
The solution
earhorn uses the local storage of the browser to store and retrieve messages between the tabs. That is possible because we run the two pages inside one browser and they both read from the same place. So in theory:

page 1 (our app) | page 2 (earhorn)
-----------------------------------
> writes to      | . checking localStorage
  localStorage   | . checking localStorage
                 | > reads from
                 |   localStorage
                 | > clears
                 |   localStorage
> writes to      | . checking localStorage
  localStorage   | . checking localStorage
                 | ... and so on

the more information you can see:
https://github.com/krasimir/lsbridge

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章