Skip to content

Commit

Permalink
fix[devtools/extension]: added a workaround for proxy content script …
Browse files Browse the repository at this point in the history
…injection in firefox
  • Loading branch information
hoxyq committed Sep 15, 2023
1 parent 54c2f2a commit 5a6feba
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
6 changes: 6 additions & 0 deletions packages/react-devtools-extensions/src/background/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ function isNumeric(str: string): boolean {

chrome.runtime.onConnect.addListener(port => {
if (port.name === 'proxy') {
// Might not be present for restricted pages in Firefox
if (port.sender?.tab?.id == null) {
// Not disconnecting it, so it would not reconnect
return;
}

// Proxy content script is executed in tab, so it should have it specified.
const tabId = port.sender.tab.id;

Expand Down
42 changes: 28 additions & 14 deletions packages/react-devtools-extensions/src/contentScripts/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,17 @@

'use strict';

window.addEventListener('unload', function ({target}) {
if (target !== window.document) {
return;
}

delete window.__REACT_DEVTOOLS_PROXY_INJECTED__;
});

let port = null;
let backendInitialized: boolean = false;

connectPort();
sayHelloToBackendManager();

// The backend waits to install the global hook until notified by the content script.
// In the event of a page reload, the content script might be loaded before the backend manager is injected.
// Because of this we need to poll the backend manager until it has been initialized.
const intervalID = setInterval(() => {
if (backendInitialized) {
clearInterval(intervalID);
} else {
sayHelloToBackendManager();
}
}, 500);

function sayHelloToBackendManager() {
window.postMessage(
{
Expand Down Expand Up @@ -76,3 +70,23 @@ function connectPort() {
port.onMessage.addListener(handleMessageFromDevtools);
port.onDisconnect.addListener(handleDisconnect);
}

// Firefox's behaviour for injecting this content script can be unpredictable
// While navigating the history, some content scripts might not be re-injected and still be alive
if (!window.__REACT_DEVTOOLS_PROXY_INJECTED__) {
window.__REACT_DEVTOOLS_PROXY_INJECTED__ = true;

connectPort();
sayHelloToBackendManager();

// The backend waits to install the global hook until notified by the content script.
// In the event of a page reload, the content script might be loaded before the backend manager is injected.
// Because of this we need to poll the backend manager until it has been initialized.
const intervalID = setInterval(() => {
if (backendInitialized) {
clearInterval(intervalID);
} else {
sayHelloToBackendManager();
}
}, 500);
}

0 comments on commit 5a6feba

Please sign in to comment.