Fix: use dataurl to inject page script

This commit is contained in:
eight 2018-10-14 02:16:48 +08:00
parent cb5cbb4d10
commit ad06551440

View File

@ -66,27 +66,27 @@ const APPLY = (() => {
// Since it's easy to spoof the browser version in pre-Quantum FF we're checking // Since it's easy to spoof the browser version in pre-Quantum FF we're checking
// for getPreventDefault which got removed in FF59 https://bugzil.la/691151 // for getPreventDefault which got removed in FF59 https://bugzil.la/691151
const EVENT_NAME = chrome.runtime.id; const EVENT_NAME = chrome.runtime.id;
if (CHROME || isOwnPage || Event.prototype.getPreventDefault || !injectPageScript()) { const usePageScript = CHROME || isOwnPage || Event.prototype.getPreventDefault ?
Promise.resolve(false) : injectPageScript();
return (el, content) => { return (el, content) => {
usePageScript.then(ok => {
if (!ok) {
// FIXME: do we have to keep el.sheet.disabled? // FIXME: do we have to keep el.sheet.disabled?
el.textContent = content; el.textContent = content;
}; } else {
}
return (el, content) => {
const detail = pageObject({ const detail = pageObject({
method: 'setStyleContent', method: 'setStyleContent',
id: el.id, id: el.id,
content content
}); });
window.dispatchEvent(new CustomEvent(EVENT_NAME, {detail})); window.dispatchEvent(new CustomEvent(EVENT_NAME, {detail}));
}
});
}; };
function injectPageScript() { function injectPageScript() {
// FIXME: does it work with XML?
const scriptContent = EVENT_NAME => { const scriptContent = EVENT_NAME => {
window.dispatchEvent(new CustomEvent(EVENT_NAME, { document.currentScript.remove();
detail: {method: 'pageScriptOK'}
}));
window.addEventListener(EVENT_NAME, function handler(e) { window.addEventListener(EVENT_NAME, function handler(e) {
const {method, id, content} = e.detail; const {method, id, content} = e.detail;
if (method === 'setStyleContent') { if (method === 'setStyleContent') {
@ -102,22 +102,25 @@ const APPLY = (() => {
} }
}, true); }, true);
}; };
let ok = false; const code = `(${scriptContent})(${JSON.stringify(EVENT_NAME)})`;
const check = e => { const src = `data:application/javascript;base64,${btoa(code)}`;
if (e.detail.method === 'pageScriptOK') { const script = document.createElement('script');
ok = true; const {resolve, promise} = deferred();
script.src = src;
script.onload = () => resolve(true);
script.onerror = () => resolve(false);
document.documentElement.appendChild(script);
return promise;
} }
};
window.addEventListener(EVENT_NAME, check, true);
try {
// eslint-disable-next-line no-eval
window.eval(`(${scriptContent})(${JSON.stringify(EVENT_NAME)})`);
} catch (err) {
// csp error
}
window.removeEventListener(EVENT_NAME, check, true);
return ok;
} }
function deferred() {
const o = {};
o.promise = new Promise((resolve, reject) => {
o.resolve = resolve;
o.reject = reject;
});
return o;
} }
function getMatchUrl() { function getMatchUrl() {