url - 用于替换部分 URL 的用户脚本

标签 url replace userscripts

我正在寻找一个用户脚本,如果在其中找到某些值,它可以替换 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/

相关文章:

java - 在 Java 中用替换减少代码

java - 替换数组列表中的字符

Javascript - 如何替换不在 HTML 标签中的空格?

javascript - 重新定义 RequireJS 模块——这可能吗?

url - EmberJS 和 URL 结构问题

javascript - 在 JavaScript 中解码 url 字符串

php - 在 URL 中传递参数(不使用 php GET)

regex - 似乎无法为 URL 垃圾邮件删除程序找到可靠的正则表达式

javascript - 为什么这个小书签不能转换为用户脚本?

javascript - 如何用 Greasemonkey 的用户脚本替换 JSON 字符串中的文本