From b0193985c53a9f51af8466b2735b6d9890f712ff Mon Sep 17 00:00:00 2001 From: EnixCoda Date: Fri, 27 Nov 2020 11:35:28 +0800 Subject: [PATCH] fix: pjax-api unecessary saving position behavior --- scripts/fix-pjax-api.js | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/scripts/fix-pjax-api.js b/scripts/fix-pjax-api.js index a6b1f96..492a9d6 100644 --- a/scripts/fix-pjax-api.js +++ b/scripts/fix-pjax-api.js @@ -1,11 +1,11 @@ /** - * This script rewrites code of pjax-api to resolve few issues on FireFox. + * This script rewrites code of pjax-api to resolve compatibility issues. * This is a bit dirty but really effective. */ const fs = require('fs').promises const path = require('path') -function modify(source = '', pairs) { +function modify(source = '', pairs = [], loose = true) { for (const [original, replace] of pairs) { if (source.includes(original)) { source = source.replace(original, replace) @@ -13,28 +13,49 @@ function modify(source = '', pairs) { throw new Error(`More than one original string found`, JSON.stringify(original)) } } else { - throw new Error(`Original string not found`, JSON.stringify(original)) + if (!loose) throw new Error(`Original string not found`, JSON.stringify(original)) } } return source } -async function fixPJAXAPI() { +async function fixPJAXAPI(loose) { const pairs = [ + // Firefox [ `void xhr.open(method, requestURL.path, true);`, `void xhr.open(method, requestURL.reference, true);`, ], + // Firefox [ `this.document = this.xhr.responseType === 'document' ? this.xhr.responseXML.cloneNode(true) : html_1.parse(this.xhr.responseText).extract();`, `this.document = this.xhr.responseType === 'document' ? this.xhr.responseXML : html_1.parse(this.xhr.responseText).extract();`, ], + // Chrome: modifying cross-context history state causes troubles + // Scroll position can still be restored without this function + [ + ` + function savePosition() { + void window.history.replaceState({ + ...window.history.state, + position: { + top: window.pageYOffset, + left: window.pageXOffset + } + }, document.title); + }`, + ` + function savePosition() { + return; + }`, + ], ] const filePath = path.resolve(__dirname, '..', `node_modules/pjax-api/dist/pjax-api.js`) const source = await fs.readFile(filePath, 'utf-8') - const modified = modify(source, pairs) + const modified = modify(source, pairs, loose) fs.writeFile(filePath, modified, 'utf-8') } -fixPJAXAPI() +const loose = process.argv.includes('loose') +fixPJAXAPI(loose)