1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This function is returned to DidInitializeServiceWorkerContextOnWorkerThread
6 // then executed, passing in dependencies as function arguments.
8 // |backgroundUrl| is the URL of the extension's background page.
9 // |wakeEventPage| is a function that wakes up the current extension's event
10 // page, then runs its callback on completion or failure.
11 // |logging| is an object equivalent to a subset of base/debug/logging.h, with
13 (function(backgroundUrl, wakeEventPage, logging) {
15 self.chrome = self.chrome || {};
16 self.chrome.runtime = self.chrome.runtime || {};
18 // Returns a Promise that resolves to the background page's client, or null
19 // if there is no background client.
20 function findBackgroundClient() {
21 return self.clients.matchAll({
22 includeUncontrolled: true,
24 }).then(function(clients) {
25 return clients.find(function(client) {
26 return client.url == backgroundUrl;
31 // Returns a Promise wrapper around wakeEventPage, that resolves on success,
32 // or rejects on failure.
33 function makeWakeEventPagePromise() {
34 return new Promise(function(resolve, reject) {
35 wakeEventPage(function(success) {
39 reject('Failed to start background client "' + backgroundUrl + '"');
44 // The chrome.runtime.getBackgroundClient function is documented in
45 // runtime.json. It returns a Promise that resolves to the background page's
46 // client, or is rejected if there is no background client or if the
47 // background client failed to wake.
48 self.chrome.runtime.getBackgroundClient = function() {
49 return findBackgroundClient().then(function(client) {
51 // Background client is already awake, or it was persistent.
55 // Event page needs to be woken.
56 return makeWakeEventPagePromise().then(function() {
57 return findBackgroundClient();
58 }).then(function(client) {
60 return Promise.reject(
61 'Background client "' + backgroundUrl + '" not found');