chromium/chrome/test/data/safe_browsing/malware_js_request_worker.js

// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// The main page sends this worker a message with a URL. This worker must
// respond with the result of attempting to connect. Unfortunately every kind of
// worker does this differently.

if (self.postMessage) {
  // This is a dedicated worker.
  onmessage = handleMessage;
} else if (self.clients) {
  // This is a ServiceWorker.
  onmessage = event => {
    // Emulate the Worker postMessage API.
    self.postMessage = message => event.ports[0].postMessage(message);
    handleMessage(event);
  }
} else {
  // This is a SharedWorker.
  onconnect = handleConnect;
}

function handleConnect(event) {
  // For shared workers, emulate the Worker postMessage() API.
  self.postMessage = message => event.ports[0].postMessage(message);
  event.ports[0].onmessage = handleMessage;
}

function handleMessage(event) {
  const url = event.data;
  runTest(url);
}

function runTest(url) {
  if ((new URL(url)).protocol == 'ws:') {
    const ws = new WebSocket(url);
    ws.onerror = () => {
      postMessage('ERROR');
    };
    ws.onopen = () => {
      postMessage('NOT BLOCKED');
    };
  } else {
    fetch(url).then(function(response) {
      postMessage('NOT BLOCKED');
    }).catch(function() {
      postMessage('ERROR');
    });
  }
}