我有以下脚本来自动跟随 Google 图像搜索结果中的 IFRAME:
// ==UserScript==
// @name Follow IFRAME in Google image search
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match http://images.google.de/imgres?*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
location.replace(document.querySelector('iframe').src)
效果很好。
现在我想让它独立于德国顶级域名。但是当我将匹配更改为
// @match http://images.google.*/imgres?*
它停止工作了。 Chrome 的 documentation @match
选项表示:
┌──────────────────────┬───────────────────────────────────────────────────────┐ │ Bad pattern │ Why it's bad │ ├──────────────────────┼───────────────────────────────────────────────────────┤ │ http://foo.*.bar/baz │ If '*' is in the host, it must be the first character │ └──────────────────────┴───────────────────────────────────────────────────────┘
如何将任何顶级域与此类限制相匹配?
最佳答案
TLDR: Use
@include
with the magic wildcard.tld
在 Tampermonkey并在 Greasemonkey @include
指令允许您使用 .tld
作为神奇的通配符。
// WORKS IN TAMPERMONKEY AND GREASEMONKEY, PROBABLY VIOLENTMONKEY TOO
//
// @include https://images.google.tld/*
其中 .tld
将匹配任何标准化顶级域。
请注意,此不适用于@match
,并且可能不适用于所有用户脚本扩展。
// DOES NOT WORK
//
// @match https://images.google.tld/*
奇怪的是,它不在 TamperMonkey 的 documentation 中(2023 年 10 月)。也许是因为它的兼容性不广泛,但使用起来却很诱人。
此外,如果您使用@include
,ESLint 会发出警告。我只是忽略它。
我认为用户脚本社区应该接受 .tld
解决方案,因为这些对我不起作用:
// DO NOT WORK
//
// @match https://images.google.tld/*
// @match https://images.google.*.*/*
虽然这些确实有效,但它们显然很糟糕:
// WORKS, BUT HORRIBLE and possibly deprecated
//
// @include /https:\/\/images\.google\.[a-z]{2,3}(\.[a-z]{2})?\/.*/
// OR
// WIDELY COMPATIBLE, BUT HORRIBLE
//
// @match https://images.google.com/*
// @match https://images.google.de/*
// @match https://images.google.fr/*
// @match https://images.google.co.uk/*
// @match https://images.google.com.my/*
// ... and 67 more lines ...
关于javascript - 如何匹配 Tampermonkey 中的任何顶级域名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34219217/