更改页面的URL参数 [英] Changing a page's URL parameters

查看:92
本文介绍了更改页面的URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在浏览器上每个YouTube视频URL的末尾添加参数&vhs=1.我尝试使用以下脚本,但是它陷入了一个循环(使&vhs=1 &vhs=1...保持keeps的状态).

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.

推荐答案

该脚本正在检查 URL的pathname setting 部分.另外,它具有至少一个语法问题.另外,使用host而不是hostname;更加健壮和便携.

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.

所以您的脚本应该像:

// ==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.


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.

这篇关于更改页面的URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆