Search code examples
javascriptgoogle-chrome-extensionchannel-api

Chrome Extension - Implementing Channels


I am trying to implement a channel with my back-end server, which is running on the Google App Engine (Python), and I am unsure how to write the front end code for Chrome. I found some code, but am unable to test as I am waiting for the back-end code to be written by my partner. I am wondering if I am implementing this correctly.

I also do not understand how the code is triggered? What triggers this channel to be created?

//The code I found which is placed in background.html:

chrome.extension.onRequest.addListener (function(request, sender, sendResponse) {
    var channel = new goog.appengine.Channel(channelToken);
    var socket = channel.open()

    socket.onopen = function() {
      // Do stuff right after opening a channel
    }

    socket.onmessage = function(evt) {
      // Do more cool stuff when a channel message comes in
    }
}); 

Solution

  • Your code as written will open a channel whenever the background page receives a request from another part of your extension (e.g, a content script).

    You probably want to open the channel as soon as the extension loads, and only then. To do this, just open the socket in your background.html JS, which runs on page load.

    For example:

    var channel = new goog.appengine.Channel(channelToken);
    var socket = channel.open()
    
    socket.onopen = function() {
      // Do stuff right after opening a channel
    }
    
    socket.onmessage = function(evt) {
      // Do more cool stuff when a channel message comes in
    }
    

    (Without the onRequest.addListener() wrapper)