javascript - 更改页面的 URL 参数

标签 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);
}

任何人都可以就如何为此目的编写脚本提供一些见解和建议吗?我似乎不知道如何摆脱无限循环问题。

最佳答案

该脚本正在检查路径名,但设置 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 网址的搜索部分中始终包含某些内容,因此此代码没问题。对于其他网站,您可能需要进行额外检查,并根据搜索最初是否为空添加 &vhs=1?vhs=1

关于javascript - 更改页面的 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065937/

相关文章:

javascript - JQuery 悬停函数超时

注入(inject) URL 的 Javascript

javascript - 如何将简单的可迭代类从 JavaScript 重写为 TypeScript?

javascript - 根据用户屏幕尺寸更改元素的位置。如何为移动设备堆叠这些元素?

java - 如何检查URL是否是本地机器?

iphone - 如何在 Safari 中获取/查看/读取当前 URL?

java - 获取URL的二级域名(java)

Android - 创建新的 View 属性并传递给 XML 复合 View 组件中的子级 - 布局中的数据绑定(bind)

javascript - 调用带有绑定(bind)到转发器的参数的 javascript 函数

sql - 从java调用带有表值参数的存储过程