我正在寻找一个用户脚本,如果在其中找到某些值,它可以替换 URL 的一部分。下面的代码似乎可以正常工作并替换 URL,但问题是 URL 更改后它会继续重新加载/刷新页面。我对这一切都是新手,我做错了什么?
// @include http://*
// @include https://*
// @run-at document-start
// ==/UserScript==
var url = window.location.href;
if (url.search("images.abc.com") >= 0) {
url = url.replace('300','620');
window.location = url;
}
最佳答案
您使用的 window.location=url
会更改窗口位置并刷新您的页面。您可以执行类似的操作来更新 url,而无需重新加载页面。
仅更改哈希值之后的内容 - 旧浏览器
document.location.hash = 'lookAtMeNow';
更改完整 URL。 Chrome、火狐、IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
以上内容将在历史记录中添加一个新条目,以便您可以按“后退”按钮返回到之前的状态。要更改 URL 而不向历史记录添加新条目,请使用
history.replaceState('data to be passed', 'Title of the page', '/test');
完整解决方案
var url = window.location.href;
if (url.search("images.abc.com") >= 0) {
url = url.replace('300','620');
/*window.location = url;*/
history.pushState('data if any', 'Title of the page if any', url);
history.replaceState('data if any', 'Title of the page if any', url);
}
关于url - 用于替换部分 URL 的用户脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51840530/