try {
var url = document.location.toString();
var updateUrl = updateQueryStringParameter(url, 'lang', 'en');
console.log(updateUrl);
console.log(url != updateUrl);
if (url != updateUrl) {
document.location = updateUrl;
}
} catch (e) {}
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
return uri + separator + key + "=" + value;
}
}
Greasemonkey script to add parameter to URL
-
19-06-2023 - |
문제
I'm not good at JS so I've been toying around with some Greasemonkey scripts I've managed to find, but they didn't perform as expected. What I want is very basic:
Check if the URL within a domain contains the variable lang
- either ?lang
or &lang
If the URL contains that variable, check its value: If the value is en
do nothing, if however the value is anything else, replace it with en
If the URL doesn't contain the variable lang
add it to the end of the URL, as in &lang=en
Any ideas?
해결책
다른 팁
You want to use window.location
. .search
contains the query in a string.
// if the query doesn't contain lang=en
if (!window.location.search.match(/[?&]lang=en(&|$)/)) {
// either replace an existing lang=... param or append it
window.location.search = window.location.search.
replace(/[?&]lang=[^&]*|$/, '&lang=en');
}
제휴하지 않습니다 StackOverflow