Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to @match a URL hash in a userscript?

I have a lot open tabs of a website - and I want to limit it to only one URL.

The problem is that the URL has # in it and I can't seem to @match it.

The URL looks like: https://xxx.xxxxxx.xxx/#/xxxxxx

I tried:

// @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;/

Any combination of * and anything after it doesn't work. :(

like image 645
Krzysztof Avatar asked Sep 21 '18 15:09

Krzysztof


1 Answers

This question is closely related to: Greasemonkey/Tampermonkey @match for a page with parameters.

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

To trigger off the hash value (officially called the "fragment"), you can either use @includenote-1 or use @match and also test the URL yourself.

So use code like:

...
// @match    *://YOUR_SERVER.COM/YOUR_PATH/
// ==/UserScript==

if ( ! /#unicorn.*/.test(location.hash) )  return;

// REST OF YOUR CODE HERE.

For this example, that code:

  • Runs : https://YOUR_SERVER.COM/YOUR_PATH/#unicorn
  • Runs : https://YOUR_SERVER.COM/YOUR_PATH/#unicorn-mode, etc.
  • Ignores: https://YOUR_SERVER.COM/YOUR_PATH/#unicom
  • Ignores: https://YOUR_SERVER.COM/YOUR_PATH/?foo=bar#unicorn (Add * at end of @match if desired.)

IMPORTANT: This is for initial page loads only. The hash can change after a page loads, and that's more complicated to deal with and not specified in this question.
So, for that kind of scenario, open a new question and refer to this one.




Notes:

  1. Unfortunately, Tampermonkey has yet to implement @include the way Greasemonkey did, so the fragment/hash is ignored even in @include and seems likely to remain that way for the near future.
like image 62
Brock Adams Avatar answered Nov 03 '22 19:11

Brock Adams