summaryrefslogtreecommitdiffstats
path: root/extensions/renderer/resources/service_worker_bindings.js
blob: 532f51ddd2b5c9520b25d695f5bb2aa4ba7197d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This function is returned to DidInitializeServiceWorkerContextOnWorkerThread
// then executed, passing in dependencies as function arguments.
//
// |backgroundUrl| is the URL of the extension's background page.
// |wakeEventPage| is a function that wakes up the current extension's event
// page, then runs its callback on completion or failure.
// |logging| is an object equivalent to a subset of base/debug/logging.h, with
// CHECK/DCHECK/etc.
(function(backgroundUrl, wakeEventPage, logging) {
  'use strict';
  self.chrome = self.chrome || {};
  self.chrome.runtime = self.chrome.runtime || {};

  // Returns a Promise that resolves to the background page's client, or null
  // if there is no background client.
  function findBackgroundClient() {
    return self.clients.matchAll({
      includeUncontrolled: true,
      type: 'window'
    }).then(function(clients) {
      return clients.find(function(client) {
        return client.url == backgroundUrl;
      });
    });
  }

  // Returns a Promise wrapper around wakeEventPage, that resolves on success,
  // or rejects on failure.
  function makeWakeEventPagePromise() {
    return new Promise(function(resolve, reject) {
      wakeEventPage(function(success) {
        if (success)
          resolve();
        else
          reject('Failed to start background client "' + backgroundUrl + '"');
      });
    });
  }

  // The chrome.runtime.getBackgroundClient function is documented in
  // runtime.json. It returns a Promise that resolves to the background page's
  // client, or is rejected if there is no background client or if the
  // background client failed to wake.
  self.chrome.runtime.getBackgroundClient = function() {
    return findBackgroundClient().then(function(client) {
      if (client) {
        // Background client is already awake, or it was persistent.
        return client;
      }

      // Event page needs to be woken.
      return makeWakeEventPagePromise().then(function() {
        return findBackgroundClient();
      }).then(function(client) {
        if (!client) {
          return Promise.reject(
            'Background client "' + backgroundUrl + '" not found');
        }
        return client;
      });
    });
  };
});