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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值