Skip to content

Commit

Permalink
"Soft reload" approach to fix file: and ftp: issues.
Browse files Browse the repository at this point in the history
  • Loading branch information
hackademix committed Aug 29, 2020
1 parent f9d4e08 commit 703d85f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 56 deletions.
71 changes: 35 additions & 36 deletions src/content/syncFetchPolicy.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,6 @@
// injected in the DOM as soon as possible.
debug("No CSP yet for non-HTTP document load: fetching policy synchronously...");

let earlyScripts = [];
let dequeueEarlyScripts = (last = false) => {
if (!(ns.canScript && earlyScripts)) return;
if (earlyScripts.length === 0) {
earlyScripts = null;
return;
}
for (let s; earlyScripts && (s = earlyScripts.shift()); ) {
debug("Restoring", s);
s.firstChild._replaced = true;
s._original.replaceWith(s);
}
}

let syncFetch = callback => {
browser.runtime.sendSyncMessage(
{id: "fetchPolicy", url, contextUrl: url},
Expand All @@ -31,24 +17,24 @@
if (UA.isMozilla && document.readyState !== "complete") {
// Mozilla has already parsed the <head> element, we must take extra steps...

let softReloading = true;
debug("Early parsing: preemptively suppressing events and script execution.");

{

// List updated by build.sh from https://hg.mozilla.org/mozilla-central/raw-file/tip/xpcom/ds/StaticAtoms.py
// whenever html5_events/html5_events.pl retrieves something new.
let eventTypes = ['abort', 'mozaccesskeynotfound', 'activate', 'afterprint', 'afterscriptexecute', 'animationcancel', 'animationend', 'animationiteration', 'animationstart', 'audioprocess', 'auxclick', 'beforecopy', 'beforecut', 'beforeinput', 'beforepaste', 'beforeprint', 'beforescriptexecute', 'beforeunload', 'blocked', 'blur', 'bounce', 'boundschange', 'broadcast', 'bufferedamountlow', 'cached', 'cancel', 'change', 'chargingchange', 'chargingtimechange', 'checking', 'click', 'close', 'command', 'commandupdate', 'complete', 'compositionend', 'compositionstart', 'compositionupdate', 'connect', 'connectionavailable', 'contextmenu', 'copy', 'cut', 'dblclick', 'dischargingtimechange', 'downloading', 'data', 'drag', 'dragdrop', 'dragend', 'dragenter', 'dragexit', 'dragleave', 'dragover', 'dragstart', 'drain', 'drop', 'error', 'finish', 'focus', 'focusin', 'focusout', 'fullscreenchange', 'fullscreenerror', 'get', 'hashchange', 'input', 'inputsourceschange', 'install', 'invalid', 'keydown', 'keypress', 'keyup', 'languagechange', 'levelchange', 'load', 'loading', 'loadingdone', 'loadingerror', 'popstate', 'merchantvalidation', 'message', 'messageerror', 'midimessage', 'mousedown', 'mouseenter', 'mouseleave', 'mouselongtap', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'mozfullscreenchange', 'mozfullscreenerror', 'mozkeydownonplugin', 'mozkeyuponplugin', 'mozpointerlockchange', 'mozpointerlockerror', 'mute', 'notificationclick', 'notificationclose', 'noupdate', 'obsolete', 'online', 'offline', 'open', 'orientationchange', 'overflow', 'pagehide', 'pageshow', 'paste', 'payerdetailchange', 'paymentmethodchange', 'pointerlockchange', 'pointerlockerror', 'popuphidden', 'popuphiding', 'popuppositioned', 'popupshowing', 'popupshown', 'processorerror', 'push', 'pushsubscriptionchange', 'readystatechange', 'rejectionhandled', 'remove', 'requestprogress', 'resourcetimingbufferfull', 'responseprogress', 'reset', 'resize', 'scroll', 'select', 'selectionchange', 'selectend', 'selectstart', 'set', 'shippingaddresschange', 'shippingoptionchange', 'show', 'squeeze', 'squeezeend', 'squeezestart', 'statechange', 'storage', 'submit', 'success', 'typechange', 'terminate', 'text', 'toggle', 'tonechange', 'touchstart', 'touchend', 'touchmove', 'touchcancel', 'transitioncancel', 'transitionend', 'transitionrun', 'transitionstart', 'underflow', 'unhandledrejection', 'unload', 'unmute', 'updatefound', 'updateready', 'upgradeneeded', 'versionchange', 'visibilitychange', 'voiceschanged', 'vrdisplayactivate', 'vrdisplayconnect', 'vrdisplaydeactivate', 'vrdisplaydisconnect', 'vrdisplaypresentchange', 'webkitanimationend', 'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend', 'wheel', 'zoom', 'begin', 'end', 'repeat', 'pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'pointerover', 'pointerout', 'pointerenter', 'pointerleave', 'gotpointercapture', 'lostpointercapture', 'devicemotion', 'deviceorientation', 'absolutedeviceorientation', 'deviceproximity', 'mozorientationchange', 'userproximity', 'devicelight', 'devicechange', 'mozvisualresize', 'mozvisualscroll', 'mozshowdropdown', 'scrollend', 'loadend', 'loadstart', 'progress', 'suspend', 'emptied', 'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata', 'waiting', 'playing', 'canplay', 'canplaythrough', 'seeking', 'seeked', 'timeout', 'timeupdate', 'ended', 'formdata', 'ratechange', 'durationchange', 'volumechange', 'addtrack', 'controllerchange', 'cuechange', 'enter', 'exit', 'encrypted', 'waitingforkey', 'keystatuseschange', 'removetrack', 'dataavailable', 'warning', 'start', 'stop', 'photo', 'gamepadbuttondown', 'gamepadbuttonup', 'gamepadaxismove', 'gamepadconnected', 'gamepaddisconnected', 'fetch', 'audiostart', 'audioend', 'soundstart', 'soundend', 'speechstart', 'speechend', 'result', 'nomatch', 'resume', 'mark', 'boundary', 'activated', 'deactivated', 'metadatachange', 'playbackstatechange', 'positionstatechange', 'supportedkeyschange', 'sourceopen', 'sourceended', 'sourceclosed', 'updatestart', 'update', 'updateend', 'addsourcebuffer', 'removesourcebuffer', 'appinstalled', 'activestatechanged', 'adapteradded', 'adapterremoved', 'alerting', 'antennaavailablechange', 'attributechanged', 'attributereadreq', 'attributewritereq', 'beforeevicted', 'busy', 'callschanged', 'cardstatechange', 'cfstatechange', 'characteristicchanged', 'clirmodechange', 'connected', 'connecting', 'connectionstatechanged', 'currentchannelchanged', 'currentsourcechanged', 'datachange', 'dataerror', 'deleted', 'deliveryerror', 'deliverysuccess', 'devicefound', 'devicepaired', 'deviceunpaired', 'dialing', 'disabled', 'disconnect', 'disconnected', 'disconnecting', 'displaypasskeyreq', 'draggesture', 'eitbroadcasted', 'emergencycbmodechange', 'enabled', 'enterpincodereq', 'evicted', 'failed', 'frequencychange', 'groupchange', 'headphoneschange', 'held', 'hfpstatuschanged', 'hidstatuschanged', 'holding', 'iccchange', 'iccdetected', 'iccinfochange', 'iccundetected', 'incoming', 'mapfolderlistingreq', 'mapgetmessagereq', 'mapmessageslistingreq', 'mapmessageupdatereq', 'mapsendmessagereq', 'mapsetmessagestatusreq', 'mousewheel', 'mozbrowserafterkeydown', 'mozbrowserafterkeyup', 'mozbrowserbeforekeydown', 'mozbrowserbeforekeyup', 'mozinterruptbegin', 'mozinterruptend', 'moznetworkdownload', 'moznetworkupload', 'moztimechange', 'newrdsgroup', 'obexpasswordreq', 'otastatuschange', 'overflowchanged', 'paint', 'pairingaborted', 'pairingconfirmationreq', 'pairingconsentreq', 'pendingchange', 'pichange', 'pschange', 'ptychange', 'pullphonebookreq', 'pullvcardentryreq', 'pullvcardlistingreq', 'radiostatechange', 'rdsdisabled', 'rdsenabled', 'readerror', 'readsuccess', 'ready', 'received', 'reloadpage', 'remoteheld', 'remoteresumed', 'requestmediaplaystatus', 'resuming', 'retrieving', 'rtchange', 'scanningstatechanged', 'scostatuschanged', 'sending', 'sent', 'speakerforcedchange', 'statuschanged', 'stkcommand', 'stksessionend', 'storageareachanged', 'ussdreceived', 'voicechange', 'websocket'];
let eventSuppressor = e => {
try {
debug("Event suppressor called for ", e.type, e.target, earlyScripts, e.target._earlyScript); // DEV_ONLY
if (!earlyScripts || document.readyState === "complete") {
debug("Stopping event suppression");
for (let et of eventTypes) document.removeEventListener(et, eventSuppressor, true);
return;
}
debug("Event suppressor called for ", e.type, e.target); // DEV_ONLY

if (!ns.canScript || e.target._earlyScript) {
if (softReloading) {
e.stopPropagation();
debug(`Suppressing ${e.type} on `, e.target); // DEV_ONLY
} else {
debug("Stopping event suppression");
for (let et of eventTypes) document.removeEventListener(et, eventSuppressor, true);
}
} catch (e) {
error(e);
Expand All @@ -58,7 +44,30 @@
for (let et of eventTypes) document.addEventListener(et, eventSuppressor, true);

ns.on("capabilities", () => {
if (!ns.canScript) {
let {readyState} = document;
debug("Readystate: %s, canScript: ", readyState, ns.canScript);
if (ns.canScript) {
let softReload = e => {
try {
debug("Soft reload", e);
removeEventListener("DOMContentLoaded", softReload, true);
let document = window.wrappedJSObject.document;
let html = document.documentElement.outerHTML;
document.open();
softReloading = false;
document.write(html);
document.close();
} catch(e) {
error(e);
}
}
if (readyState === "loading") {
debug("Deferring softReload to DOMContentLoaded...");
addEventListener("DOMContentLoaded", softReload, true);
} else {
softReload();
}
} else {
try {
for (let node of document.querySelectorAll("*")) {
let evAttrs = [...node.attributes].filter(a => a.name.toLowerCase().startsWith("on"));
Expand All @@ -68,6 +77,7 @@
node.setAttributeNodeNS(a);
}
}
softReloading = false;
} catch (e) {
error(e);
}
Expand All @@ -76,21 +86,11 @@
}

addEventListener("beforescriptexecute", e => {
if (!e.isTrusted) return;
debug(e.type, e.target);
if (earlyScripts) {
let s = e.target;
if (s._replaced) {
debug("Replaced script found");
dequeueEarlyScripts(true);
return;
}
let replacement = document.createRange().createContextualFragment(s.outerHTML);
replacement._original = s;
s._earlyScript = true;
earlyScripts.push(replacement);
if (softReloading) {
e.preventDefault();
dequeueEarlyScripts(true);
debug("Blocked early script");
debug("Blocked early script", s);
}
}, true);
}
Expand All @@ -112,5 +112,4 @@
error("Background page not ready yet, retrying to fetch policy...")
}
}
dequeueEarlyScripts();
}
19 changes: 0 additions & 19 deletions src/lib/SyncMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,6 @@

if (MOZILLA) {

// In order to cope with inconsistencies in XHR synchronicity,
// allowing scripts to be executed (especially with synchronous loads
// or when other extensions manipulate the DOM early) we additionally
// suspend on beforescriptexecute events

let startTime = Date.now(); // DEV_ONLY
let suspendURL = url + "&suspend=true";
let suspended = 0;
Expand All @@ -240,22 +235,8 @@
console.debug("sendSyncMessage resume #%s/%s - %sms", id, suspended, Date.now() - startTime); // DEV_ONLY
};

let domSuspender = new MutationObserver(records => {
console.debug("sendSyncMessage suspending on ", records)
suspend();
});
domSuspender.observe(document, {childList: true, subtree: true});

let bodySuspender = e => {
console.debug("Suspending on DOMContentLoaded");
suspend();
};

addEventListener("DOMContentLoaded", bodySuspender, true);
let finalize = () => {
console.debug("sendSyncMessage finalizing");
domSuspender.disconnect();
removeEventListener("DOMContentLoaded", bodySuspender, true);
};

// on Firefox we first need to send an async message telling the
Expand Down
3 changes: 2 additions & 1 deletion src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@
"run_at": "document_start",
"matches": ["file://*/*", "ftp://*/*"],
"js": [
"lib/SyncMessage.js",
"content/syncFetchPolicy.js"
]
},
Expand All @@ -89,6 +88,7 @@
"js": [
"lib/UA.js",
"lib/browser-polyfill.js",
"lib/SyncMessage.js",
"lib/log.js",
"lib/uuid.js",
"lib/sha256.js",
Expand All @@ -106,6 +106,7 @@
"content/sanitizePaste.js"
]
},

{
"run_at": "document_start",
"matches": ["ftp://*/*"],
Expand Down

0 comments on commit 703d85f

Please sign in to comment.