2015-07-19 47 views
0

我有一些代码,我想运行mywebsite.com/x.html (其中x可能是任何东西)。如何让一些代码在`.html`网页上运行?

下面这段代码(我希望)可以找到与该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> 

我怎样才能使它在开始提到的特定网页上运行?

+1

开始通过删除那些'

0

你就可以用当前的URL段纯JavaScript与此代码:

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

所以如果你的链接是mywebsite.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 
    } 
} 
+0

该代码仍然可以在所有页面(以及所有域)上运行 - 对大多数页面来说,它们不会有太大的作用。 – MT0

3

几件事情:

  1. 限制操作只是.html页面,无论是检查location.pathname(见下文)
    或使用@include。 EG:

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

    对于精度和性能,我建议使用@match超过@include

  2. 几乎总是@match指令末尾需要通配符。 EG:

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

    注意通配符是@include小号更加灵活,但它们都是“安全的”,并在@match s以后进行得更快。

  3. 不能在用户脚本中放置直接HTML标记,就像那个<script>一样。无论如何,在这种情况下根本不需要。

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

  5. 不要使用“eval”字符串setTimeout。这具有性能,故障排除和安全问题 - 如果它可以工作的话。
    问题的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); 
    } 
} 
相关问题