javascript - 如何匹配 Tampermonkey 中的任何顶级域名?

标签 javascript greasemonkey tampermonkey

我有以下脚本来自动跟随 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/

相关文章:

jQuery click() 在 Greasemonkey/Tampermonkey 脚本中不起作用

javascript - 在 JavaScript 中实现动态作用域

javascript - 在 laravel 和 vue 中使用 axios 上传文件和输入数据

javascript - 如何使用jquery和greasemonkey在谷歌分析中选择一个选项?

javascript - 如何在大括号内的代码块周围使用 for 循环?

javascript - 如何选择具有动态 ID 的父元素的嵌套子元素?

javascript - Chrome/Tampermonkey 用户脚本存储在文件系统的什么位置?

javascript - React <Link> 是如何工作的? <Link> 中的绝对路径

javascript - 动态添加和删除项目以选择jquery

javascript - 为什么 jQuery 在我的 GreaseMonkey 脚本中加载两次