Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - Changing a page's URL parameters

I want to add the parameter &vhs=1 at the end of each YouTube video URL on my browser. I have tried using the following script but it gets stuck in a loop (keeps adding &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);
}

Can anyone offer some insights and advice as to how I can write the script for this purpose? I can't seem to figure out how to get out of the infinite loop problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That script is checking the pathname but setting the search part of the URL. In addition, it has at least one syntax problem. Also, use host rather than hostname; it's more robust and portable.

So your script would be like:

// ==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);
}

Note that YouTube URL's always have something in the search part of the URL, so this code is fine. For other sites, you may need an additional check and to add either &vhs=1 or ?vhs=1 depending on whether the search was initially blank.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...