如何在 `.html` 网页上获取 运行 的一些代码?

How to get some code to run on just `.html` webpages?

我有一些代码想 运行 mywebsite.com/x.html (其中 x 可以是任何东西)。

下面这段代码(我希望)会在网页上找到 ID 为 'mybutton' 的按钮,并在延迟 1 秒后自动点击它:

<script>
  window.onload = function() {
      setTimeout('document.getElementById('mybutton').click()', 1000);
  }
</script>

我用 Google 搜索并找到了 Tampermonkey Chrome 扩展,但唯一的问题是我不知道如何 运行 它只在上面提到的特定网页上。

我只是将我的代码放在 Tampermonkey 给出的示例布局的末尾,得到了这个:

// ==UserScript==
// @name         My Fancy New Userscript
// @namespace    http://your.homepage/
// @version      0.1
// @description  enter something useful
// @author       You
// @match        http://website.com
// @grant        none
// ==/UserScript==

<script>
  window.onload = function() {
      setTimeout('document.getElementById('mybutton').click()', 1000);
  }
</script>

如何在开头提到的特定网页上运行?

您可以定义 Tampermonkey 代码将 运行 使用星号作为通配符的网页。
所以这使得它适用于您网站的任何子目录:

// @match   http://www.mywebsite.com/*

要使其仅适用于 html 页,请更改通配符:

// @match   http://www.mywebsite.com/*.html

您可以使用以下代码通过纯 javascript 获取当前 url 段:

var url = window.location.pathname.split( '/' );

因此,如果您的 link 是我的网站。com/about,那么大约将是 url[1]

您可以定义要执行代码的页面数组,然后检查当前 url

var url = window.location.pathname.split( '/' );
var pages = ['home', 'about', 'services'];

for(var i=0; i<pages.length; i++) {
    if(pages[i] === url[1]) {
        // execute your code
    }
}

几件事:

  1. 将操作限制为仅 .html,请选中 location.pathname(见下文)
    或使用 @include。例如:

    // @include http://website.com/*.html
    

    为了精度和性能,我建议使用 @match 而不是 @include

  2. 您几乎总是 需要在 @match 指令末尾使用通配符 。例如:

    // @match http://website.com/*
    

    请注意,通配符在 @include 秒内更加灵活,但它们 "safer" 并且在 @match 秒内执行速度更快。

  3. 不能像 <script> 那样在用户脚本中直接放置 HTML 标签。反正这种情况下根本不需要

  4. 您很少需要在用户脚本中使用 window.onload在大多数情况下,默认情况下,用户脚本会在理想时间触发。

  5. 不要在 setTimeout 中使用 "eval" 字符串 。这有性能、故障排除和安全问题——如果它能工作的话。
    问题的 setTimeout 使用了大部分,还有一个语法错误。

  6. 直接 .click() 调用有时会起作用,many times not.
    如果不行,发送a click event.

  7. 避免任意计时器。 EG:setTimeout(..., 1000);
    这是一种 "Time bomb" 代码形式。它有时会起作用。其他时候,页面会延迟。当它起作用时,它可能会大大降低您的脚本速度。
    使用an AJAX aware utility见下面的代码。


将它们放在一起,使用 jQuery 和一个标准实用程序来节省工作并提高稳健性,您的脚本将是这样的:

// ==UserScript==
// @name     _Auto click the X button on Y pages
// @match    http://website.com/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

//--- Does the *path* part of the URL end in `.html`?
if (/\.html$/i.test (location.pathname) ) {
    waitForKeyElements ("#mybuttonID", clicktargetButton);

    function clicktargetButton (jNode) {
        var clickEvent  = document.createEvent ('MouseEvents');
        clickEvent.initEvent ('click', true, true);
        jNode[0].dispatchEvent (clickEvent);
    }
}