---
title: "ServiceWorker Communication via MessageChannel"
description: "Two-way communication between ServiceWorker and main thread using MessageChannel API. Practical notes and code examples on."
url: "https://h3manth.com/scribe/serviceworker-communication-via-messagechannel/"
canonical_url: "https://h3manth.com/scribe/serviceworker-communication-via-messagechannel/"
markdown_url: "https://h3manth.com/scribe/blog/serviceworker-communication-via-messagechannel.md"
publishDate: "2016-02-13T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["javascript","service-worker","web-api"]
word_count: 121
reading_time_minutes: 1
x_markdown_tokens: 387
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# ServiceWorker Communication via MessageChannel

> Two-way communication between ServiceWorker and main thread using MessageChannel API. Practical notes and code examples on.

Two-way communication between ServiceWorker and main thread is easily possible with [MessageChannel](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) API.

## In app.js

Create a `sendMessage` method:

```javascript
function sendMessage(message) {
  return new Promise((resolve, reject) => {
    const messageChannel = new MessageChannel();
    
    messageChannel.port1.onmessage = function(event) {
      resolve(`Received a direct message from the ServiceWorker: ${event.data}`);
    };
    
    navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2])
  });
}

## In sw.js

Receive and respond to the message:
javascript
self.addEventListener('message', function(event) {
  console.log(`Received a message from main thread: ${event.data}`);
  event.ports[0].postMessage(`Roger that! - "${event.data}"`);
});
```

## Usage

From your `app.js`, send a message and get a response:

```javascript
var log = console.log.bind(console);
var error = console.error.bind(console);

sendMessage('hello').then(log, error).catch(error);

This would log:

Received message from main thread: Hello
Received direct message from service worker: Roger that! - "Hello"
```
