Skip to content

Instantly share code, notes, and snippets.

@gwokae
Last active May 11, 2020 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwokae/77a896865deea912591092167ae3cb00 to your computer and use it in GitHub Desktop.
Save gwokae/77a896865deea912591092167ae3cb00 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name reactjs.org switch languages
// @version 0.1
// @description keep the browseing path when switch language on reactjs.org
// @author Leonard Lin <https://github.com/gwokae>+
// @updateURL https://gist.github.com/gwokae/77a896865deea912591092167ae3cb00/raw/reactjs.org.switch.lang.user.js
// @match https://*.reactjs.org/*
// @grant none
// ==/UserScript==
const DELAY = 1000;
(function() {
'use strict';
let qs = getQueryString();
let debounceId;
document.addEventListener('click', ({target}) => {
let el = target
if (!el.matches('a[href]')) {
el = el.closest('a[href]');
}
if(!el) return;
const current = getQueryString(el);
if(current === '/languages') {
if(debounceId) {
clearTimeout(debounceId);
}
debounceId = setTimeout(updateHref(qs, function(){ debounceId = 0 }), DELAY);
} else if (current) {
qs = current;
}
});
})();
function updateHref(qs, done) {
return function() {
Array
.from(document.querySelectorAll('a[href][lang]'))
.forEach((el) => {
if(el.href.endsWith('reactjs.org/')) {
el.href = el.href.slice(0, el.href.length - 1) + qs;
}
});
}
}
function getQueryString({origin, href} = document.location) {
if(origin && href) {
return href.replace(origin, '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment