我已经从几个例子中破解了这个。预期的行为是将字符串“?foo”附加到 barsite.com 的 url 末尾,然后终止。
实际行为是附加到 URL,然后不断刷新页面并附加字符串。我对脚本/js 了解不够,无法弄清楚为什么这表现得像一个循环。
我不确定我的正则表达式是罪魁祸首,还是语句正文中的某些内容。
// ==UserScript==
// @name Barfoo Hack
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Add ?foo to barsite.com urls
// @author DC
// @match *://*.barsite.com/*
// @run-at document-start
// @grant none
// ==/UserScript==
var oldUrlPath = window.location.pathname;
if ( ! /\?foo/.test (oldUrlPath) ) {
var newURL = window.location.protocol + "//" +
window.location.host + oldUrlPath + "?foo" +
window.location.search +
window.location.hash;
window.location.replace (newURL);
}
最佳答案
感谢 Amadan,解决方案是在 window.location.search
而不是 window.location.pathname
更新后的例子:
// ==UserScript==
// @name Barfoo Hack
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Add ?foo to barsite.com urls
// @author DC
// @match *://*.barsite.com/*
// @run-at document-start
// @grant none
// ==/UserScript==
var oldUrlPath = window.location.pathname;
var testPath = window.location.search;
if ( ! /\?foo/.test (testPath) ) {
var newURL = window.location.protocol + "//" +
window.location.host + oldUrlPath + "?foo" +
window.location.search +
window.location.hash;
window.location.replace (newURL);
}
关于javascript - 用户脚本在页面刷新时循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48316554/