【问题标题】:Changing a page's URL parameters更改页面的 URL 参数
【发布时间】:2013-04-10 13:31:27
【问题描述】:

我想在浏览器上每个 YouTube 视频 URL 的末尾添加参数 &vhs=1。我曾尝试使用以下脚本,但它卡在一个循环中(不断添加&vhs=1&vhs=1...)。

// ==UserScript==
// @name        Youtube Tape Mode
// @namespace   _pc
// @match       *://*.youtube.com/watch?*
// @run-at      document-start
// ==/UserScript==

var oldUrlPath  = window.location.pathname;

/*--- Test that "&vhs=1" is at end of URL, excepting any "hashes"
or searches.
*/
if ( ! /\&vhs=1$/.test (oldUrlPath) ) {

    var newURL  = window.location.protocol + "//"
                + window.location.hostname
                + oldUrlPath 
                + window.location.search.replace + "&vhs=1"
                + window.location.hash
            ;
    /*-- replace() puts the good page in the history instead of the
        bad page.
    */
    window.location.replace (newURL);
}

谁能就我如何为此目的编写脚本提供一些见解和建议?我似乎无法弄清楚如何摆脱无限循环问题。

【问题讨论】:

    标签: javascript url parameters greasemonkey tampermonkey


    【解决方案1】:

    该脚本检查 pathname 但设置 URL 的search 部分。此外,它至少有一个语法问题。另外,使用host 而不是hostname;它更加健壮和便携。

    所以你的脚本会是这样的:

    // ==UserScript==
    // @name        Youtube Tape Mode
    // @match       *://*.youtube.com/watch?*
    // @run-at      document-start
    // @grant       none
    // ==/UserScript==
    
    var oldUrlSearch  = window.location.search;
    
    /*--- Test that "&vhs=1" is at end of URL, excepting any "hashes"
    or searches.
    */
    if ( ! /\&vhs=1$/.test (oldUrlSearch) ) {
    
        var newURL  = window.location.protocol + "//"
                    + window.location.host
                    + window.location.pathname
                    + oldUrlSearch + "&vhs=1"
                    + window.location.hash
                    ;
        /*-- replace() puts the good page in the history instead of the
            bad page.
        */
        window.location.replace (newURL);
    }
    

    请注意,YouTube URL 的 search 部分总是有一些内容,所以这段代码没问题。对于其他网站,您可能需要额外检查并添加 &vhs=1 或 ?vhs=1,具体取决于搜索最初是否为空白。

    【讨论】:

    猜你喜欢
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2012-06-02
    • 2019-12-31
    相关资源
    最近更新 更多