更改页面的URL参数

时间:2013-04-17 17:01:29

标签: javascript url parameters greasemonkey tampermonkey

我想在浏览器的每个YouTube视频网址末尾添加参数&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);
}

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

1 个答案:

答案 0 :(得分:1)

该脚本正在检查 pathname设置网址的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网址的search部分始终包含一些内容,因此此代码很好。对于其他网站,您可能需要额外检查并添加&vhs=1?vhs=1,具体取决于搜索最初是否为空白。