【问题标题】:Userscript to replace part of URL [duplicate]用于替换部分 URL 的用户脚本 [重复]
【发布时间】:2018-08-14 11:39:01
【问题描述】:

如果在其中找到某些值,我正在寻找一个替换 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;
}

【问题讨论】:

    标签: url replace userscripts


    【解决方案1】:

    您正在使用window.location=url,它会更改窗口位置并刷新您的页面。您可以执行类似的操作来更新 url 而无需重新加载页面。

    仅更改哈希后的内容 - 旧浏览器

    document.location.hash = 'lookAtMeNow';  
    

    更改完整网址。铬、火狐、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);
    }
    

    【讨论】:

    • 我不明白。你能更新现有的代码吗?
    • 我已经更新了解决方案。请不要忘记投票赞成这个答案。谢谢。
    • 也接受这个答案。
    猜你喜欢
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 2011-12-07
    相关资源
    最近更新 更多