<!DOCTYPE html>
<html>

  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>BroadcastChannel API</title>
  <meta name="description" content="BroadcastChannel APIis a new API used to communicate between same-origin tabs opened by the same user.">

  <link href="https://fonts.googleapis.com/css?family=Secular+One|Nunito|Mononoki" rel="stylesheet"> 
  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://localhost:4000/broadcastchannel-api/">
  <link rel="alternate" type="application/rss+xml" title="mahdi" href="http://localhost:4000/feed.xml" />

  

  <!--<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>-->

  <script>
    var channel = new BroadcastChannel('egg');

    channel.addEventListener('message', message => {
      alert('Got a message from the other tab:\n' + message.data);
    });
  </script>
</head>



  <body>

    <header class="site-header">

  <h1>
    <a class='site-title' href='/'>
      mahdi
    </a>
  </h1>

  <nav>
    <p>
      <a href="/snippets">snippets</a>
      <a href="/art">pictures</a>
    </p>
    <!--<p class='categories'>-->
      <!---->
        <!---->
        <!--<a href="">art</a>-->
        <!---->
      <!---->
        <!---->
      <!---->
    <!--</p>-->
    <p>
      <a href='mailto:mdibaiee@pm.me'>email</a>
      <a href='https://git.mahdi.blog/mahdi'>git</a>
      <a href='https://www.librarything.com/profile/mdibaiee'>librarything</a>
      <a href="http://localhost:4000/feed.xml">feed</a>
    </p>
  </nav>

</header>


    <div class="page-content">
      <div class="wrapper">
        <h1 class="page-heading"></h1>
        
          <div class='post lang-en'>

  <div class="post-header">
    <h1 class="post-title"><p>BroadcastChannel API</p>
</h1>
    
    <p class="post-meta">
      <span>Apr 2, 2015</span>
      
      • <span>Reading time: 4  minutes</span>
    </p>
  </div>

  <article class="post-content">
    <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API">BroadcastChannel API</a>
is a new API used to communicate between same-origin tabs opened by the same user.</p>

<h1 id="why">Why</h1>
<p>Let’s say you open two GitHub tabs, the <a href="https://github.com/rust-lang/rust">rust repository</a> and <a href="https://github.com/stars">your stars</a> page. You decide to star the awesome rust repository, but then you have to
refresh your stars page to see your new star. That’s sad. There must be a way for GitHub to refresh
your stars page in case you star something in another tab, right?</p>

<p><img src="/img/broadcast-channels.jpg" alt="Broadcast Channels, SATISFIED" /></p>

<h1 id="show-me-something">Show me something!</h1>
<p>Okay, open another page of my blog in a new tab. Now open up your console and enter this:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">channel</span><span class="p">.</span><span class="nx">postMessage</span><span class="p">(</span><span class="dl">'</span><span class="s1">Anybody hears me?</span><span class="dl">'</span><span class="p">);</span></code></pre></figure>

<p>Boom.</p>

<p>I’ve put this code in my <code class="language-plaintext highlighter-rouge">&lt;head&gt;</code>, pretty simple:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">channel</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">BroadcastChannel</span><span class="p">(</span><span class="dl">'</span><span class="s1">egg</span><span class="dl">'</span><span class="p">);</span>

<span class="nx">channel</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">message</span><span class="dl">'</span><span class="p">,</span> <span class="nx">message</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">alert</span><span class="p">(</span><span class="dl">'</span><span class="s1">Got a message from the other tab:</span><span class="se">\n</span><span class="dl">'</span> <span class="o">+</span> <span class="nx">message</span><span class="p">.</span><span class="nx">data</span><span class="p">);</span>

  <span class="c1">// Egg</span>
  <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">'</span><span class="s1">header</span><span class="dl">'</span><span class="p">).</span><span class="nx">classList</span><span class="p">.</span><span class="nx">add</span><span class="p">(</span><span class="dl">'</span><span class="s1">channel</span><span class="dl">'</span><span class="p">);</span>
<span class="p">});</span></code></pre></figure>

<h1 id="how">How</h1>
<p>BroadcastChannels are pretty easy, here I’m going over the small details.</p>

<h2 id="creating-channels">Creating channels</h2>
<p>BroadcastChannels are constructed with a single argument, their name. Browsing contexts should use
this name to communicate over a specified channel. There’s no limit to how many channels you can create.</p>

<p>In the first sentence of article I said it’s used to communicate between tabs, but it’s actually “browsing contexts”.
<a href="http://www.w3.org/TR/html5/browsers.html#browsing-context">Browsing contexts</a> are any environments owning a <code class="language-plaintext highlighter-rouge">Document</code>, e.g. tabs, windows, iframes, etc.</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">channel</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">BroadcastChannel</span><span class="p">(</span><span class="dl">'</span><span class="s1">star</span><span class="dl">'</span><span class="p">);</span></code></pre></figure>

<p>Channels have only one property, <code class="language-plaintext highlighter-rouge">name</code>.</p>

<h2 id="methods">Methods</h2>
<p>Channels have two methods:</p>

<h3 id="postmessagedata-anything">#postMessage(data: Anything)</h3>
<p>This is the method used to broadcast a message to everyone subscribed to this channel. <code class="language-plaintext highlighter-rouge">data</code> can be any kind of Object.</p>

<h3 id="close">#close()</h3>
<p>This method is used to leave a channel, in case you don’t want to hear from the channel anymore.</p>

<p>Try leaving <code class="language-plaintext highlighter-rouge">channel</code> from my blog pages, and posting messages with others.</p>

<h2 id="events">Events</h2>
<p>Channels inherit from <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code class="language-plaintext highlighter-rouge">EventTarget</code></a>, so you can use  <code class="language-plaintext highlighter-rouge">addEventListener</code>, <code class="language-plaintext highlighter-rouge">removeEventListener</code> and <code class="language-plaintext highlighter-rouge">dispatchEvent</code> methods.</p>

<p>Channels have only one event:</p>

<h3 id="message">message</h3>
<p>The event object passed to this event is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent"><code class="language-plaintext highlighter-rouge">MessageEvent</code></a> with the <code class="language-plaintext highlighter-rouge">data</code> property set to the actual message sent using <code class="language-plaintext highlighter-rouge">postMessage</code>.</p>

<hr />

<h1 id="another-example">Another example</h1>
<p>Let’s Fix GitHub
—————-</p>

<p>Okay, let’s try something cool, I promise you will love it. Open a browser with <a href="http://caniuse.com/#feat=broadcastchannel">BroadcastChannel support</a> and Install <a href="http://www.greasespot.net/">GreaseMonkey</a>.</p>

<p>You have to add two scripts, one for repository pages, and one for the stars page.</p>

<p>Click “New User Script”, and fill the inputs like this:</p>

<p><img src="/img/greasemonkey-new-user-script.png" alt="GreaseMonkey New User Script" /></p>

<p><img src="/img/greasemonkey-github-stars.png" alt="GreaseMonkey New Script" /></p>

<p>In the Script Editor, enter this:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="c1">// join the "Stars" channel</span>
<span class="kd">var</span> <span class="nx">channel</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">BroadcastChannel</span><span class="p">(</span><span class="dl">'</span><span class="s1">Stars</span><span class="dl">'</span><span class="p">);</span>

<span class="c1">// reload the page when someone from a github.com tab broadcasts a message</span>
<span class="nx">channel</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">message</span><span class="dl">'</span><span class="p">,</span> <span class="nx">message</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">location</span><span class="p">.</span><span class="nx">reload</span><span class="p">();</span>
<span class="p">});</span></code></pre></figure>

<p>Now create another script and fill the form like this:</p>

<p><img src="/img/greasemonkey-github-repositories.png" alt="GreaseMonkey New Script" /></p>

<p>Use this code:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="c1">// join the "Stars" channel</span>
<span class="kd">var</span> <span class="nx">channel</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">BroadcastChannel</span><span class="p">(</span><span class="dl">'</span><span class="s1">Stars</span><span class="dl">'</span><span class="p">);</span>

<span class="c1">// once the star/unstar forms are submitted, broadcast a message to</span>
<span class="c1">// all github.com tabs</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">'</span><span class="s1">.starring-container form</span><span class="dl">'</span><span class="p">).</span><span class="nx">submit</span><span class="p">(</span><span class="nx">e</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">channel</span><span class="p">.</span><span class="nx">postMessage</span><span class="p">(</span><span class="dl">'</span><span class="s1">refresh</span><span class="dl">'</span><span class="p">);</span>
<span class="p">});</span></code></pre></figure>

<p>Save, refresh your pages and Voila! You can now Star/Unstar any repository while your stars page
is open, and your stars page will refresh immediately.</p>

<hr />

<p>That’s it, I really like this API as it’s best of both worlds, simple and useful.</p>

<p>There are a lot of things which can be done with help of BroadcastChannels, I would love to hear your feedback on this API.</p>

  </article>

  <div class="share-page">
    Share in

    <a href="https://twitter.com/intent/tweet?text=BroadcastChannel API&url=http://localhost:4000/broadcastchannel-api/&via=&related=" rel="nofollow" target="_blank" title="Share on Twitter">Twitter</a>
    <a href="https://facebook.com/sharer.php?u=http://localhost:4000/broadcastchannel-api/" rel="nofollow" target="_blank" title="Share on Facebook">Facebook</a>
    <a href="https://plus.google.com/share?url=http://localhost:4000/broadcastchannel-api/" rel="nofollow" target="_blank" title="Share on Google+">Google+</a>
</div>

  
  <div id="commento"></div>
  <script defer
    src="//commento.mahdi.blog/js/commento.js">
  </script>

  <script src="/js/heading-links.js"></script>
</div>

        
      </div>
    </div>

  </body>

</html>