instant style injection via synchronous XHR
This commit is contained in:
parent
3d0b733e9a
commit
38290c22f7
|
@ -956,6 +956,12 @@
|
|||
"optionsAdvancedNewStyleAsUsercss": {
|
||||
"message": "Write new style as usercss"
|
||||
},
|
||||
"optionsAdvancedStyleViaXhr": {
|
||||
"message": "Instant inject mode"
|
||||
},
|
||||
"optionsAdvancedStyleViaXhrNote": {
|
||||
"message": "Enable this if you encounter flashing of unstyled content (FOUC) when browsing, which is especially noticeable with dark themes.\n\nThe technical reason is that Chrome/Chromium postpones asynchronous communication of extensions, in a usually meaningless attempt to improve page load speed, potentially causing styles to be late to apply. To circumvent this, since web extensions are not provided a synchronous API, Stylus provides this option to utilize the \"deprecated\" synchronous XMLHttpRequest web API to fetch applicable styles. There shouldn't be any detrimental effects, since the request is fulfilled within a few milliseconds while the page is still being downloaded from the server.\n\nNevertheless, Chromium will print a warning in devtools' console. Right-clicking a warning, and hiding them, will prevent future warnings from being shown."
|
||||
},
|
||||
"optionsBadgeDisabled": {
|
||||
"message": "Background color when disabled"
|
||||
},
|
||||
|
|
88
background/style-via-xhr.js
Normal file
88
background/style-via-xhr.js
Normal file
|
@ -0,0 +1,88 @@
|
|||
/* global API CHROME prefs */
|
||||
'use strict';
|
||||
|
||||
// eslint-disable-next-line no-unused-expressions
|
||||
CHROME && (async () => {
|
||||
const prefId = 'styleViaXhr';
|
||||
const blobUrlPrefix = 'blob:' + chrome.runtime.getURL('/');
|
||||
const stylesToPass = {};
|
||||
|
||||
await prefs.initializing;
|
||||
toggle(prefId, prefs.get(prefId));
|
||||
prefs.subscribe([prefId], toggle);
|
||||
|
||||
function toggle(key, value) {
|
||||
if (!chrome.declarativeContent) { // not yet granted in options page
|
||||
value = false;
|
||||
}
|
||||
if (value) {
|
||||
const reqFilter = {
|
||||
urls: ['<all_urls>'],
|
||||
types: ['main_frame', 'sub_frame'],
|
||||
};
|
||||
chrome.webRequest.onBeforeRequest.addListener(prepareStyles, reqFilter);
|
||||
chrome.webRequest.onHeadersReceived.addListener(passStyles, reqFilter, [
|
||||
'blocking',
|
||||
'responseHeaders',
|
||||
chrome.webRequest.OnHeadersReceivedOptions.EXTRA_HEADERS,
|
||||
].filter(Boolean));
|
||||
} else {
|
||||
chrome.webRequest.onBeforeRequest.removeListener(prepareStyles);
|
||||
chrome.webRequest.onHeadersReceived.removeListener(passStyles);
|
||||
}
|
||||
if (!chrome.declarativeContent) {
|
||||
return;
|
||||
}
|
||||
chrome.declarativeContent.onPageChanged.removeRules([prefId], async () => {
|
||||
if (!value) return;
|
||||
chrome.declarativeContent.onPageChanged.addRules([{
|
||||
id: prefId,
|
||||
conditions: [
|
||||
new chrome.declarativeContent.PageStateMatcher({
|
||||
pageUrl: {urlContains: ':'},
|
||||
}),
|
||||
],
|
||||
actions: [
|
||||
new chrome.declarativeContent.RequestContentScript({
|
||||
allFrames: true,
|
||||
js: [
|
||||
'/content/style-via-xhr.js',
|
||||
// This sets them to run earlier than document_start
|
||||
...chrome.runtime.getManifest().content_scripts[0].js,
|
||||
],
|
||||
}),
|
||||
],
|
||||
}]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param {chrome.webRequest.WebRequestBodyDetails} req */
|
||||
function prepareStyles(req) {
|
||||
API.getSectionsByUrl(req.url).then(sections => {
|
||||
const str = JSON.stringify(sections);
|
||||
if (str !== '{}') {
|
||||
stylesToPass[req.requestId] = URL.createObjectURL(new Blob([str])).slice(blobUrlPrefix.length);
|
||||
setTimeout(cleanUp, 600e3, req.requestId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @param {chrome.webRequest.WebResponseHeadersDetails} req */
|
||||
function passStyles(req) {
|
||||
const blobId = stylesToPass[req.requestId];
|
||||
if (blobId) {
|
||||
const {responseHeaders} = req;
|
||||
responseHeaders.push({
|
||||
name: 'Set-Cookie',
|
||||
value: `${chrome.runtime.id}=${blobId}`,
|
||||
});
|
||||
return {responseHeaders};
|
||||
}
|
||||
}
|
||||
|
||||
function cleanUp(key) {
|
||||
const blobId = stylesToPass[key];
|
||||
delete stylesToPass[key];
|
||||
if (blobId) URL.revokeObjectURL(blobUrlPrefix + blobId);
|
||||
}
|
||||
})();
|
|
@ -20,6 +20,7 @@ self.INJECTED !== 1 && (() => {
|
|||
/** @type chrome.runtime.Port */
|
||||
let port;
|
||||
let lazyBadge = IS_FRAME;
|
||||
let parentDomain;
|
||||
|
||||
// the popup needs a check as it's not a tab but can be opened in a tab manually for whatever reason
|
||||
if (!IS_TAB) {
|
||||
|
@ -42,24 +43,25 @@ self.INJECTED !== 1 && (() => {
|
|||
window.addEventListener(orphanEventId, orphanCheck, true);
|
||||
}
|
||||
|
||||
let parentDomain;
|
||||
|
||||
prefs.subscribe(['disableAll'], (key, value) => doDisableAll(value));
|
||||
if (IS_FRAME) {
|
||||
prefs.subscribe(['exposeIframes'], updateExposeIframes);
|
||||
}
|
||||
|
||||
function onInjectorUpdate() {
|
||||
if (!isOrphaned) {
|
||||
updateCount();
|
||||
updateExposeIframes();
|
||||
const onOff = prefs[styleInjector.list.length ? 'subscribe' : 'unsubscribe'];
|
||||
onOff(['disableAll'], updateDisableAll);
|
||||
if (IS_FRAME) onOff(['exposeIframes'], updateExposeIframes);
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
return STYLE_VIA_API ?
|
||||
API.styleViaAPI({method: 'styleApply'}) :
|
||||
API.getSectionsByUrl(getMatchUrl()).then(styleInjector.apply);
|
||||
async function init() {
|
||||
if (STYLE_VIA_API) {
|
||||
await API.styleViaAPI({method: 'styleApply'});
|
||||
} else {
|
||||
const styles = Array.isArray(window.STYLES) && window.STYLES[0] ||
|
||||
await API.getSectionsByUrl(getMatchUrl());
|
||||
delete window.STYLES;
|
||||
await styleInjector.apply(styles);
|
||||
}
|
||||
}
|
||||
|
||||
function getMatchUrl() {
|
||||
|
@ -138,7 +140,7 @@ self.INJECTED !== 1 && (() => {
|
|||
}
|
||||
}
|
||||
|
||||
function doDisableAll(disableAll) {
|
||||
function updateDisableAll(key, disableAll) {
|
||||
if (STYLE_VIA_API) {
|
||||
API.styleViaAPI({method: 'prefChanged', prefs: {disableAll}});
|
||||
} else {
|
||||
|
@ -146,22 +148,18 @@ self.INJECTED !== 1 && (() => {
|
|||
}
|
||||
}
|
||||
|
||||
function fetchParentDomain() {
|
||||
return parentDomain ?
|
||||
Promise.resolve() :
|
||||
API.getTabUrlPrefix()
|
||||
.then(newDomain => {
|
||||
parentDomain = newDomain;
|
||||
});
|
||||
}
|
||||
|
||||
function updateExposeIframes() {
|
||||
if (!prefs.get('exposeIframes') || window === parent || !styleInjector.list.length) {
|
||||
document.documentElement.removeAttribute('stylus-iframe');
|
||||
async function updateExposeIframes(key, value = prefs.get('exposeIframes')) {
|
||||
const attr = 'stylus-iframe';
|
||||
const el = document.documentElement;
|
||||
if (!el) return; // got no styles so styleInjector didn't wait for <html>
|
||||
if (!value || window === parent || !styleInjector.list.length) {
|
||||
el.removeAttribute(attr);
|
||||
} else {
|
||||
fetchParentDomain().then(() => {
|
||||
document.documentElement.setAttribute('stylus-iframe', parentDomain);
|
||||
});
|
||||
if (!parentDomain) parentDomain = await API.getTabUrlPrefix();
|
||||
// Check first to avoid triggering DOM mutation
|
||||
if (el.getAttribute(attr) !== parentDomain) {
|
||||
el.setAttribute(attr, parentDomain);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
18
content/style-via-xhr.js
Normal file
18
content/style-via-xhr.js
Normal file
|
@ -0,0 +1,18 @@
|
|||
'use strict';
|
||||
|
||||
// eslint-disable-next-line no-unused-expressions
|
||||
self.INJECTED !== 1 &&
|
||||
!(document instanceof XMLDocument && !chrome.app) && // this is STYLE_VIA_API
|
||||
new RegExp(`(^|\\s|;)${chrome.runtime.id}=\\s*([-\\w]+)\\s*(;|$)`).test(document.cookie) &&
|
||||
(() => {
|
||||
const url = 'blob:' + chrome.runtime.getURL(RegExp.$2);
|
||||
const xhr = new XMLHttpRequest();
|
||||
document.cookie = `${chrome.runtime.id}=1; max-age=0`;
|
||||
try {
|
||||
xhr.open('GET', url, false); // synchronous
|
||||
xhr.send();
|
||||
// guarding against an implicit global variable for a DOM element with id="STYLES"
|
||||
window.STYLES = [JSON.parse(xhr.response)];
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {}
|
||||
})();
|
|
@ -9,6 +9,7 @@ self.prefs = self.INJECTED === 1 ? self.prefs : (() => {
|
|||
'disableAll': false, // boss key
|
||||
'exposeIframes': false, // Add 'stylus-iframe' attribute to HTML element in all iframes
|
||||
'newStyleAsUsercss': false, // create new style in usercss format
|
||||
'styleViaXhr': false, // early style injection to avoid FOUC
|
||||
|
||||
// checkbox in style config dialog
|
||||
'config.autosave': true,
|
||||
|
|
|
@ -23,6 +23,9 @@
|
|||
"identity",
|
||||
"<all_urls>"
|
||||
],
|
||||
"optional_permissions": [
|
||||
"declarativeContent"
|
||||
],
|
||||
"background": {
|
||||
"scripts": [
|
||||
"js/polyfill.js",
|
||||
|
@ -53,6 +56,7 @@
|
|||
"background/usercss-helper.js",
|
||||
"background/usercss-install-helper.js",
|
||||
"background/style-via-api.js",
|
||||
"background/style-via-xhr.js",
|
||||
"background/search-db.js",
|
||||
"background/update.js",
|
||||
"background/openusercss-api.js"
|
||||
|
|
16
options.html
16
options.html
|
@ -232,9 +232,25 @@
|
|||
</h1>
|
||||
</div>
|
||||
<div class="items">
|
||||
<label class="chromium-only">
|
||||
<span i18n-text="optionsAdvancedStyleViaXhr">
|
||||
<a data-cmd="note"
|
||||
i18n-title="optionsAdvancedStyleViaXhrNote"
|
||||
href="#"
|
||||
class="svg-inline-wrapper"
|
||||
tabindex="0">
|
||||
<svg class="svg-icon info"><use xlink:href="#svg-icon-help"/></svg>
|
||||
</a>
|
||||
</span>
|
||||
<span class="onoffswitch">
|
||||
<input type="checkbox" id="styleViaXhr" class="slider">
|
||||
<span></span>
|
||||
</span>
|
||||
</label>
|
||||
<label>
|
||||
<span i18n-text="optionsAdvancedExposeIframes">
|
||||
<a data-cmd="note"
|
||||
i18n-data-title="optionsAdvancedExposeIframesNote"
|
||||
i18n-title="optionsAdvancedExposeIframesNote"
|
||||
href="#"
|
||||
class="svg-inline-wrapper"
|
||||
|
|
|
@ -342,6 +342,7 @@ html:not(.firefox):not(.opera) #updates {
|
|||
#message-box.note {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
#message-box.note > div {
|
||||
|
|
|
@ -38,6 +38,27 @@ if (FIREFOX && 'update' in (chrome.commands || {})) {
|
|||
});
|
||||
}
|
||||
|
||||
if (CHROME) {
|
||||
// Show the option as disabled until the permission is actually granted
|
||||
const el = $('#styleViaXhr');
|
||||
el.addEventListener('click', () => {
|
||||
if (el.checked && !chrome.declarativeContent) {
|
||||
chrome.permissions.request({permissions: ['declarativeContent']}, ok => {
|
||||
if (chrome.runtime.lastError || !ok) {
|
||||
el.checked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!chrome.declarativeContent) {
|
||||
prefs.initializing.then(() => {
|
||||
if (prefs.get('styleViaXhr')) {
|
||||
el.checked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// actions
|
||||
$('#options-close-icon').onclick = () => {
|
||||
top.dispatchEvent(new CustomEvent('closeOptions'));
|
||||
|
@ -79,7 +100,7 @@ document.onclick = e => {
|
|||
e.preventDefault();
|
||||
messageBox({
|
||||
className: 'note',
|
||||
contents: target.title,
|
||||
contents: target.dataset.title,
|
||||
buttons: [t('confirmClose')],
|
||||
});
|
||||
}
|
||||
|
@ -233,6 +254,7 @@ function splitLongTooltips() {
|
|||
.map(s => s.replace(/(.{50,80}(?=.{40,}))\s+/g, '$1\n'))
|
||||
.join('\n');
|
||||
if (newTitle !== el.title) {
|
||||
el.dataset.title = el.title;
|
||||
el.title = newTitle;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user