用户脚本在页面刷新时循环

Userscript Looping On Page Refresh

我已经从几个例子中一起破解了这个。预期的行为是将字符串“?foo”附加到 barsite.com 的 url 末尾,然后终止。

实际行为是附加到 URL,然后不断刷新页面并附加字符串。我对 scripting/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);
}