改变页面的URL参数(Changing a page's URL parameters)

2019-08-31 10:20发布

我想补充的参数&vhs=1 ,在我的浏览器的每个YouTube视频网址的结尾。 我曾尝试使用下面的脚本尝试,但它陷在一个循环(不断添加&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);
}

任何人都可以提供一些见解和建议,我怎么能为这个目的所写剧本? 我似乎无法弄清楚如何走出死循环的问题。

Answer 1:

该脚本检查 pathname ,但设置 search URL的一部分。 此外,它至少有一个语法问题。 此外,使用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 URL的一部分,因此,这段代码的罚款。 对于其他网站,则可能需要额外的检查,并添加任何&vhs=1?vhs=1取决于搜索是否最初是空白的。



文章来源: Changing a page's URL parameters