Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Obsolete] Fix messaging in chrome extension pages (#2846) #2863

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/database-types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2017 Google Inc.
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -122,7 +122,7 @@ export interface Reference extends Query {

export interface ServerValue {
TIMESTAMP: Object;
increment(delta: number) : Object;
increment(delta: number): Object;
}

export interface ThenableReference extends Reference, Promise<Reference> {}
6 changes: 3 additions & 3 deletions packages/firebase/index.d.ts
Original file line number Diff line number Diff line change
@@ -6920,15 +6920,15 @@ declare namespace firebase.database.ServerValue {
* ```
*/
var TIMESTAMP: Object;

/**
* Returns a placeholder value that can be used to atomically increment the
* Returns a placeholder value that can be used to atomically increment the
* current database value by the provided delta.
*
* @param delta the amount to modify the current value atomically.
* @return a placeholder value for modifying data atomically server-side.
*/
function increment(delta: number) : Object;
function increment(delta: number): Object;
}

/**
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2017 Google Inc.
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
64 changes: 64 additions & 0 deletions packages/messaging/src/controllers/sw-controller.test.ts
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@ import { getFakeFirebaseDependencies } from '../testing/fakes/firebase-dependenc
import '../testing/setup';
import { SwController, BgMessageHandler } from './sw-controller';
import * as tokenManagementModule from '../core/token-management';
import * as utilModule from '@firebase/util';
import { Stub } from '../testing/sinon-types';
import { Writable, ValueOf, DeepPartial } from 'ts-essentials';
import { MessagePayload } from '../interfaces/message-payload';
@@ -218,6 +219,38 @@ describe('SwController', () => {
expect(postMessageSpy).to.have.been.calledOnceWith(expectedMessage);
});

it('sends a message to chrome extension clients if a chrome extension client is visible', async () => {
const client: Writable<WindowClient> = (await self.clients.openWindow(
'chrome-extension://testExtensionId/popup.html'
))!;
const backgroundClient: Writable<WindowClient> = (await self.clients.openWindow(
'chrome-extension://testExtensionId/background_page.html'
))!;
client.visibilityState = 'visible';
stub(utilModule, 'getBrowserExtensionRuntime').returns({
getBackgroundClient() {
return backgroundClient;
}
});
const postMessageSpy = spy(client, 'postMessage');

await callEventListener(
makeEvent('push', {
data: {
json: () => NOTIFICATION_MESSAGE_PAYLOAD
}
})
);

const expectedMessage: InternalMessage = {
firebaseMessaging: {
type: MessageType.PUSH_RECEIVED,
payload: NOTIFICATION_MESSAGE_PAYLOAD
}
};
expect(postMessageSpy).to.have.been.calledOnceWith(expectedMessage);
});

it('does not send a message to window clients if window clients are hidden', async () => {
const client = (await self.clients.openWindow('https://example.org'))!;
const postMessageSpy = spy(client, 'postMessage');
@@ -241,6 +274,37 @@ describe('SwController', () => {
});
});

it('does not send a message to chrome extension background pages if background page is visible', async () => {
const client: Writable<WindowClient> = (await self.clients.openWindow(
'chrome-extension://testExtensionId/background_page.html'
))!;
client.visibilityState = 'visible';
stub(utilModule, 'getBrowserExtensionRuntime').returns({
getBackgroundClient() {
return client;
}
});
const postMessageSpy = spy(client, 'postMessage');
const showNotificationSpy = spy(self.registration, 'showNotification');

await callEventListener(
makeEvent('push', {
data: {
json: () => NOTIFICATION_MESSAGE_PAYLOAD
}
})
);

expect(postMessageSpy).not.to.have.been.called;
expect(showNotificationSpy).to.have.been.calledWith('message title', {
...NOTIFICATION_MESSAGE_PAYLOAD.notification,
data: {
...NOTIFICATION_MESSAGE_PAYLOAD.notification!.data,
[FCM_MSG]: NOTIFICATION_MESSAGE_PAYLOAD
}
});
});

it('displays a notification if a window client does not exist', async () => {
const showNotificationSpy = spy(self.registration, 'showNotification');

41 changes: 32 additions & 9 deletions packages/messaging/src/controllers/sw-controller.ts
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ import {
import { FCM_MSG, DEFAULT_VAPID_KEY } from '../util/constants';
import { MessageType, InternalMessage } from '../interfaces/internal-message';
import { dbGet } from '../helpers/idb-manager';
import { Unsubscribe } from '@firebase/util';
import { Unsubscribe, getBrowserExtensionRuntime } from '@firebase/util';
import { sleep } from '../helpers/sleep';
import { FirebaseApp } from '@firebase/app-types';
import { isConsoleMessage } from '../helpers/is-console-message';
@@ -157,7 +157,7 @@ export class SwController implements FirebaseMessaging, FirebaseService {
}

const clientList = await getClientList();
if (hasVisibleClients(clientList)) {
if (await hasVisibleClients(clientList)) {
// App in foreground. Send to page.
return sendMessageToWindowClients(clientList, payload);
}
@@ -291,14 +291,37 @@ async function getWindowClient(url: string): Promise<WindowClient | null> {
* @returns If there is currently a visible WindowClient, this method will
* resolve to true, otherwise false.
*/
function hasVisibleClients(clientList: WindowClient[]): boolean {
return clientList.some(
client =>
client.visibilityState === 'visible' &&
// Ignore chrome-extension clients as that matches the background pages
// of extensions, which are always considered visible for some reason.
!client.url.startsWith('chrome-extension://')
async function hasVisibleClients(clientList: WindowClient[]): Promise<boolean> {
const checkedClientList = await Promise.all(
clientList.map(
async client =>
client.visibilityState === 'visible' &&
// Ignore browser extension clients as that matches the background pages
// of extensions, which are always considered visible for some reason.
!(await isBackgroundClient(client))
)
);

return checkedClientList.some(item => item);
}

/**
* @returns If client is the background page of browser extension, this method will
* resolve to true, otherwise false.
*/
async function isBackgroundClient(client: WindowClient): Promise<boolean> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: how about isBackgroundExtension or isExtensionBackgroundClient. Just to make clear we're talking in the extension context

const runtime = getBrowserExtensionRuntime();

if (runtime) {
try {
const backgroundClient = await runtime.getBackgroundClient();
return client === backgroundClient;
} catch {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enkot,
Can we have a debug log here on the error and error message so it would be easier for folks to debug if they hit this path and wanted to get information?

return false;
}
}

return false;
}

/**
2 changes: 1 addition & 1 deletion packages/performance/src/services/perf_logger.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
3 changes: 1 addition & 2 deletions packages/performance/src/services/perf_logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -176,7 +176,6 @@ export function logNetworkRequest(networkRequest: NetworkRequest): void {
setTimeout(() => sendLog(networkRequest, ResourceType.NetworkRequest), 0);
}


function serializer(
resource: NetworkRequest | Trace,
resourceType: ResourceType
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
2 changes: 1 addition & 1 deletion packages/performance/src/services/settings_service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
2 changes: 1 addition & 1 deletion packages/performance/src/services/transport_service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
2 changes: 1 addition & 1 deletion packages/performance/src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
2 changes: 1 addition & 1 deletion packages/performance/src/utils/string_merger.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
2 changes: 1 addition & 1 deletion packages/performance/src/utils/string_merger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2019 Google Inc.
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
19 changes: 15 additions & 4 deletions packages/util/src/environment.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2017 Google Inc.
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -73,21 +73,32 @@ export function isBrowser(): boolean {
}

/**
* Detect browser extensions (Chrome and Firefox at least).
* Returns browser extension runtime or undefined if it's not defined.
* @return browser extension runtime
*/
interface BrowserRuntime {
id?: unknown;
getBackgroundClient: Function;
}
declare const chrome: { runtime?: BrowserRuntime };
declare const browser: { runtime?: BrowserRuntime };
export function isBrowserExtension(): boolean {
export function getBrowserExtensionRuntime(): BrowserRuntime | undefined {
const runtime =
typeof chrome === 'object'
? chrome.runtime
: typeof browser === 'object'
? browser.runtime
: undefined;
return typeof runtime === 'object' && runtime.id !== undefined;
return typeof runtime === 'object' && runtime.id !== undefined
? runtime
: undefined;
}

/**
* Detect browser extensions (Chrome and Firefox at least).
*/
export function isBrowserExtension(): boolean {
return !!getBrowserExtensionRuntime();
}

/**