【问题标题】:How to @match a URL hash in a userscript?如何@match用户脚本中的URL哈希?
【发布时间】:2019-02-26 00:58:05
【问题描述】:

我有很多打开的网站标签 - 我想将其限制为只有一个 URL。

问题是 URL 中有 #,我似乎无法 @match 它。

网址如下:https://xxx.xxxxxx.xxx/#/xxxxxx

我试过了:

// @match https://xxx.xxxxxx.xxx/#/xxxxxx - doesnt work

// @match https://xxx.xxxxxx.xxx/* - works - but works on all tabs

// @match https://xxx.xxxxxx.xxx/*/xxxxxx -doesnt work;/

// @match https://xxx.xxxxxx.xxx/\#/xxxxxx -doesnt work;/

* 和它之后的任何内容的任何组合都不起作用。 :(

【问题讨论】:

    标签: url match greasemonkey userscripts tampermonkey


    【解决方案1】:

    这个问题与:Greasemonkey/Tampermonkey @match for a page with parameters密切相关。

    @matchonly works on the protocol/scheme, host, and pathname of a URL.

    要触发哈希值(官方为called the "fragment"),您可以使用@includenote-1 或使用@match 并测试URL自己。

    所以使用如下代码:

    ...
    // @match    *://YOUR_SERVER.COM/YOUR_PATH/
    // ==/UserScript==
    
    if ( ! /#unicorn.*/.test(location.hash) )  return;
    
    // REST OF YOUR CODE HERE.
    

    对于这个例子,那个代码:

    • 运行 :https://YOUR_SERVER.COM/YOUR_PATH/#unicorn
    • Runs :https://YOUR_SERVER.COM/YOUR_PATH/#unicorn-mode
    • 忽略:https://YOUR_SERVER.COM/YOUR_PATH/#unicom
    • 忽略:https://YOUR_SERVER.COM/YOUR_PATH/?foo=bar#unicorn(如果需要,在@match 末尾添加*。)

    重要提示:这仅适用于初始页面加载。hash 可以在页面加载后更改,处理起来更复杂,并且未在此问题中指定。
    因此,对于这种情况,请打开一个新问题并参考此问题。




    注意事项:

    1. 不幸的是,Tampermonkey 尚未像 Greasemonkey 那样实现 @include,因此即使在 @includeseems likely to remain that way for the near future 中,片段/哈希也会被忽略。

    【讨论】:

    • 谢谢你,这并不能完全解决我的问题,但我从你的帖子中猜想 - 现在不可能。关于此解决方法的两个注意事项:1)它将在每个页面上添加到“活动脚本计数”+1 - 尽管他们没有使用此特定脚本 2)它应该是 if ( ! /#\/unicorn.*/.test(location.哈希))返回;对于我的情况:) 再次非常感谢你:)
    • @Krzysztof,不客气。唉,直到 Tampermonkey 的开发人员解决了脚本计数问题。 @include 方法可以解决这个问题,如果它有效,它可能会在 Violentmonkey 上(尚未检查)。
    • @Krzysztof,如果这不能完全解决您的问题,请打开一个包含其他问题的新问题。包含minimal reproducible example 和/或指向目标页面的链接。
    猜你喜欢
    • 2012-05-01
    • 2012-10-07
    • 2016-06-16
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    相关资源
    最近更新 更多