Changing a page's URL parameters

前端 未结 1 1999
离开以前
离开以前 2020-12-07 04:14

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 (

1条回答
  •  -上瘾入骨i
    2020-12-07 05:13

    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.

    0 讨论(0)
提交回复
热议问题