import nullthrows from 'nullthrows';
import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants';
import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
import {IS_FIREFOX} from '../utils';
function injectScriptSync(src) {
let code = '';
const request = new XMLHttpRequest();
request.addEventListener('load', function() {
code = this.responseText;
});
request.open('GET', src, false);
request.send();
const script = document.createElement('script');
script.textContent = code;
nullthrows(document.documentElement).appendChild(script);
nullthrows(script.parentNode).removeChild(script);
}
function injectScriptAsync(src) {
const script = document.createElement('script');
script.src = src;
script.onload = function() {
script.remove();
};
nullthrows(document.documentElement).appendChild(script);
}
let lastDetectionResult;
window.addEventListener('message', function onMessage({data, source}) {
if (source !== window || !data) {
return;
}
switch (data.source) {
case 'react-devtools-detector':
lastDetectionResult = {
hasDetectedReact: true,
reactBuildType: data.reactBuildType,
};
chrome.runtime.sendMessage(lastDetectionResult);
break;
case 'react-devtools-extension':
if (data.payload?.type === 'fetch-file-with-cache') {
const url = data.payload.url;
const reject = value => {
chrome.runtime.sendMessage({
source: 'react-devtools-content-script',
payload: {
type: 'fetch-file-with-cache-error',
url,
value,
},
});
};
const resolve = value => {
chrome.runtime.sendMessage({
source: 'react-devtools-content-script',
payload: {
type: 'fetch-file-with-cache-complete',
url,
value,
},
});
};
fetch(url, {cache: 'force-cache'}).then(
response => {
if (response.ok) {
response
.text()
.then(text => resolve(text))
.catch(error => reject(null));
} else {
reject(null);
}
},
error => reject(null),
);
}
break;
case 'react-devtools-inject-backend':
injectScriptAsync(
chrome.runtime.getURL('build/react_devtools_backend.js'),
);
break;
}
});
window.addEventListener('pageshow', function({target}) {
if (!lastDetectionResult || target !== window.document) {
return;
}
chrome.runtime.sendMessage(lastDetectionResult);
});
const injectScript = IS_FIREFOX ? injectScriptSync : injectScriptAsync;
if (sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true') {
injectScript(chrome.runtime.getURL('build/renderer.js'));
}
switch (document.contentType) {
case 'text/html':
case 'application/xhtml+xml': {
injectScript(chrome.runtime.getURL('build/installHook.js'));
break;
}
}
if (typeof exportFunction === 'function') {
exportFunction(
text => {
return new window.Promise((resolve, reject) =>
window.navigator.clipboard.writeText(text).then(resolve, reject),
);
},
window.wrappedJSObject.__REACT_DEVTOOLS_GLOBAL_HOOK__,
{defineAs: 'clipboardCopyText'},
);
}