Skip to content

Commit

Permalink
Merge branch 'mv3-dapp-sendMessage-after-SW-inactivity' into dapp_act…
Browse files Browse the repository at this point in the history
…ion_replay_improvements
  • Loading branch information
jpuri authored Oct 26, 2022
2 parents 40793dd + bbd5cff commit e7ad374
Showing 1 changed file with 36 additions and 13 deletions.
49 changes: 36 additions & 13 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* global chrome */

/**
* @file The entry point for the web extension singleton process.
*/
Expand Down Expand Up @@ -48,7 +46,7 @@ import rawFirstTimeState from './first-time-state';
import getFirstPreferredLangCode from './lib/get-first-preferred-lang-code';
import getObjStructure from './lib/getObjStructure';
import setupEnsIpfsResolver from './lib/ens-ipfs/setup';
import { getPlatform } from './lib/util';
import { checkForError, getPlatform } from './lib/util';
/* eslint-enable import/first */

const { sentry } = global;
Expand Down Expand Up @@ -94,25 +92,50 @@ const PHISHING_WARNING_PAGE_TIMEOUT = ONE_SECOND_IN_MILLISECONDS;
/**
* In case of MV3 we attach a "onConnect" event listener as soon as the application is initialised.
* Reason is that in case of MV3 a delay in doing this was resulting in missing first connect event after service worker is re-activated.
*
* @param remotePort
*/

const initApp = async (remotePort) => {
browser.runtime.onConnect.removeListener(initApp);
await initialize(remotePort);
log.info('MetaMask initialization complete.');
};

const throwErrorIfLastErrorFound = () => {
const err = checkForError();
if (err) {
throw err;
}
};

/**
* Sends a message to the dapp(s) content script to signal it can connect to MetaMask background as
* the backend is not active. It is required to re-connect dapps after service worker re-activates.
*/
const sendReadyMessageToActiveTab = async () => {
try {
const tabs = await browser.tabs.query({
active: true,
currentWindow: true,
});
throwErrorIfLastErrorFound();

if (!tabs?.[0]?.id) {
return;
}

await browser.tabs.sendMessage(tabs[0].id, {
name: EXTENSION_MESSAGES.READY,
});
throwErrorIfLastErrorFound();
} catch (err) {
log.error(err);
}
};

if (isManifestV3) {
browser.runtime.onConnect.addListener(initApp);
// Message below signals content script in DAPPS to connect to metamask background as backend is not active
// It is required to re-connect DAPPS after service worker re-activation
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{ name: EXTENSION_MESSAGES.READY },
() => undefined,
);
});
sendReadyMessageToActiveTab();
} else {
// initialization flow
initialize().catch(log.error);
Expand Down

0 comments on commit e7ad374

Please sign in to comment.