我想在浏览器上每个 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/