Moved backend injection logic to content script

This commit is contained in:
Stephanie Ding
2019-09-10 17:22:04 -07:00
parent 2c98af77c3
commit c93038fabe
2 changed files with 28 additions and 22 deletions
+3 -8
View File
@@ -1,14 +1,9 @@
/* global chrome */
export default function inject(scriptName: string, done: ?Function) {
export default function inject(scriptName: string, done: ? Function) {
const source = `
// the prototype stuff is in case document.createElement has been modified
(function () {
var script = document.constructor.prototype.createElement.call(document, 'script');
script.src = "${scriptName}";
script.charset = "utf-8";
document.documentElement.appendChild(script);
script.parentNode.removeChild(script);
window.postMessage({ source: 'react-devtools-inject-backend', type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
})()
`;
@@ -21,4 +16,4 @@ export default function inject(scriptName: string, done: ?Function) {
done();
}
});
}
}
+25 -14
View File
@@ -1,9 +1,15 @@
/* global chrome */
import nullthrows from 'nullthrows';
import {installHook} from 'react-devtools-shared/src/hook';
import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants';
import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
import {
installHook
} from 'react-devtools-shared/src/hook';
import {
SESSION_STORAGE_RELOAD_AND_PROFILE_KEY
} from 'react-devtools-shared/src/constants';
import {
sessionStorageGetItem
} from 'react-devtools-shared/src/storage';
function injectCode(code) {
const script = document.createElement('script');
@@ -24,16 +30,21 @@ let lastDetectionResult;
// So instead, the hook will use postMessage() to pass message to us here.
// And when this happens, we'll send a message to the "background page".
window.addEventListener('message', function(evt) {
if (
evt.source === window &&
evt.data &&
evt.data.source === 'react-devtools-detector'
) {
lastDetectionResult = {
hasDetectedReact: true,
reactBuildType: evt.data.reactBuildType,
};
chrome.runtime.sendMessage(lastDetectionResult);
if (evt.source === window && evt.data) {
if (evt.data.source === 'react-devtools-detector') {
lastDetectionResult = {
hasDetectedReact: true,
reactBuildType: evt.data.reactBuildType,
};
chrome.runtime.sendMessage(lastDetectionResult);
} else if (evt.data.source === 'react-devtools-inject-backend') {
//Inject backend
var script = document.constructor.prototype.createElement.call(document, 'script');
script.src = chrome.runtime.getURL('build/backend.js');
script.charset = "utf-8";
document.documentElement.appendChild(script);
script.parentNode.removeChild(script);
}
}
});
@@ -86,4 +97,4 @@ if (sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true') {
// devtools are installed (and skip its suggestion to install the devtools).
injectCode(
';(' + installHook.toString() + '(window))' + saveNativeValues + detectReact,
);
);