Roll src/third_party/skia 2440fcd:4de8c3a
[chromium-blink-merge.git] / extensions / renderer / resources / service_worker_bindings.js
blob532f51ddd2b5c9520b25d695f5bb2aa4ba7197d0
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.
7 //
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
12 // CHECK/DCHECK/etc.
13 (function(backgroundUrl, wakeEventPage, logging) {
14 'use strict';
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,
23 type: 'window'
24 }).then(function(clients) {
25 return clients.find(function(client) {
26 return client.url == backgroundUrl;
27 });
28 });
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) {
36 if (success)
37 resolve();
38 else
39 reject('Failed to start background client "' + backgroundUrl + '"');
40 });
41 });
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) {
50 if (client) {
51 // Background client is already awake, or it was persistent.
52 return client;
55 // Event page needs to be woken.
56 return makeWakeEventPagePromise().then(function() {
57 return findBackgroundClient();
58 }).then(function(client) {
59 if (!client) {
60 return Promise.reject(
61 'Background client "' + backgroundUrl + '" not found');
63 return client;
64 });
65 });
67 });