单击“刷新”用户脚本除非有输入,否则每分钟都按一次? [英] Userscript to Click a "Refresh" button every minute except when there is input?

查看:98
本文介绍了单击“刷新”用户脚本除非有输入,否则每分钟都按一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Tampermonkey脚本,该脚本会经常(最好是每分钟)单击页面的刷新按钮。



如果



原因是我们正在使用需要工作的网站,及时跟踪收到的客户请求,但该站点只有一个集成的刷新按钮,需要手动单击该按钮,而不会自动刷新。



有些浏览器插件可以满足我的需要,但是它们会刷新整个网页,从而导致其失去之前已经完成的重要信息或设置。 (使用网站上的刷新按钮不会发生这种情况。)



所以我发现的是setInterval和.click函数。
我设置的是以下有时有用但有时无效的东西。
但是,即使禁用Tampermonkey,每次执行都不会停止。

  // == UserScript == 
// @name票务系统-自动刷新
// @namespace http://tampermonkey.net/
// @version 0.1
// @description试图占领世界!
// @作者您
// @match https://my*******.***.****mand.com/*
// @不授予任何权限
// == / UserScript ==

setInterval(function(){document.getElementById( buttonOcLMZKwM8KoKda967hf2B0_11)。click();},10000);

//结束

我所做的工作可能存在一些重大缺陷以上,但正如我所说,我没有使用javascript的经验。同样,所用的时间是进行测试以快速查看其是否有效。



您可能会看到我已经被刷新部分卡住了,所以打字时的停止部分甚至还没有完成。



我还使用了

  document.getElementById( buttonOcLMZKwM8KoKda967hf2B0_11) 

很有可能目标失败,因为当您再次登录时网站倾向于更改此ID。因此,我尝试使用以下方法来做到这一点:

  document.querySelector(’[title = Refresh]’); 

但这似乎根本不起作用,即使按钮的标题是Refresh。 / p>

这是网站上的完整按钮HTML:

 < button type = button id = buttonOcLMZKwM8KoKda967hf2B0_11 data-sap-ui = buttonOcLMZKwM8KoKda967hf2B0_11 
data-sap-automation-id = OcLMZKwM8KoKda967hf2B0 title =刷新 $ = -disabled = false tabindex = 0 class = sapUiBtn sapUiBtnIconOnly sapUiBtnLite sapUiBtnS width-button-form sapUiBtnStd>
< img id = buttonOcLMZKwM8KoKda967hf2B0_11-img src = https://.........TbRefresh.png
alt =刷新 class = sapUiBtnIco> < / button>

我将非常感谢我能得到的任何帮助。

解决方案

开始和停止轮询,或间隔单击等。只是:


  1. 存储 setInterval()调用的值。

    EG: var myTimer = setInterval(someFunction,1000);

  2. 将该值传递给

    EG: clearInterval(myTimer);

当然,用户界面是最难的部分。我想:


  1. 在屏幕右上方放置一个状态和控制按钮。

  2. 绑定键盘快捷键即可在无需鼠标的情况下切换循环。

以下用户脚本可以完成上述所有操作,加:


  1. 在循环的每次迭代上单击刷新按钮。

  2. 停止/

  3. 在按下 F9 时停止/重新启动(取决于焦点所在的位置)。

  4. 在选择或键入表单控件之一时停止循环。

  5. 单击刷新按钮时重新启动循环。

这里是一个完整的有效用户脚本(这只是 ******上方的部分块。)。

要查看其运行效果,请运行代码段。



  // == UserScript == // @name _Click按钮定期使用开始/停止控件// @match *://YOUR_SERVER.COM/YOUR_PATH/*// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min。 js // @grant GM_addStyle // == / UserScript == // ---初始化刷新按钮循环和控件。var rfrshBtnSel ='button [title = Refresh]'; // refreshvar的jQuery选择器rfrshTmr = LoopManager(clickRefreshButton,1000); // 1000 ms == 1秒.var loopStBtn = LoopButtonManager(rfrshTmr.toggle); rfrshTmr.setCallbacks(loopStBtn.start,loopStBtn.stop,loopStBtn.error); rfrshTmr.start(); //开始循环刷新btn click。$(window).keydown(keyboardShortcutHandler); //-在使用某些窗体控件时,停止刷新计时器:$( body)。on(单击keydown焦点粘贴滚动,输入,文本区域,选择,rfrshTmr.stop); // ---单击刷新按钮,(重新)启动刷新计时器:$( body)。on( click,rfrshBtnSel ,rfrshTmr.start); function clickRefreshButton(){var refreshBtn = $(rfrshBtnSel);如果(refreshBtn.length === 1)clickNode(refreshBtn); else loopStBtn.error(未找到刷新按钮!);}功能keyboardShortcutHandler(zEvent){if(zEvent.which == 120){//在F9上,切换Loop状态。 rfrshTmr.toggle();返回false; } return true;} function clickNode(jNode){var clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent(点击,是,是); jNode [0] .dispatchEvent(clickEvent);}函数LoopManager(callbackFnc,intrvlMillisec,bAutoStart,... optParams){var _thisInterval = null; var _startCB = null,_stopCB = null,_errorCB = null;如果(bAutoStart)_start();函数_start(){如果(!_thisInterval){_thisInterval = setInterval(callbackFnc,intrvlMillisec,... optParams); } if(_startCB)_startCB(); }函数_stop(){clearInterval(_thisInterval); _thisInterval = null;如果(_stopCB)_stopCB(); }函数_toggle(){如果(_thisInterval)_stop();否则_start(); }函数_setCallbacks(startCB,stopCB,errorCB){_startCB = startCB; _stopCB = stopCB; _errorCB = errorCB; } return {start:_start,stop:_stop,setCallbacks:_setCallbacks,toggle:_toggle};}函数LoopButtonManager(clickCB){var _btnNode = $(’#tmStartStopBtn');如果(_btnNode.length === 0){_btnNode = $(`< button id = tmStartStopBtn type = button class = tmRefreshRunning>< span> TBD< / span>(F9)< / button>`).appendTo( body); } var _spanNode = _btnNode.find( span); _btnNode.click(clickCB);函数_start(){setButtonDisplay( Running, tmRefreshRunning); }函数_stop(){setButtonDisplay( Stopped, tmRefreshStopped); }函数_error(errMess){console.error( TM: + errMess); setButtonDisplay(查看控制台!, tmError); }函数setButtonDisplay(btnText,btnClass){_spanNode.text(btnText); _btnNode.removeClass();如果(btnClass)_btnNode.addClass(btnClass); } return {start:_start,stop:_stop,error:_error};} GM_addStyle(`#tmStartStopBtn {位置:绝对;顶部:0;右侧:0;字体大小:18px;边距:5px;不透明度:0.9; z -index:1100;填充:5px 20px;颜色:黑色;光标:指针;} .tmRefreshRunning {背景:橙色;} .tmRefreshStopped {背景:青柠;} .tmError {背景:红色;}`); / *** ****************************************************** **********************该块下的所有内容都是模拟目标页面。 **************这不是用户脚本的一部分。 ****************************************************** **************************** / $('button [title = Refresh]')。click(function(){$(this) .attr( id,'spelunk'+ Math.random()); $(#StatusNd)。text( Refreshed: +(new Date()+))。replace(/ \s * \(。+ \)/,));}));  

  div {保证金:0 0 1ex 1em;宽度:20em;填充:0.5ex 1em 0 1em;边框:1px深绿色; border-radius:1ex;} label {margin:0 0 0 2em; } label [for = Bar] {display:inline-block;垂直对齐:顶部; }按钮,#StatusNd {裕度:0 0 1ex 2em; }  

 < script src = // ajax.googleapis .com / ajax / libs / jquery / 2.1.0 / jquery.min.js>< / script>< script src = https://greasyfork.org/scripts/44560-gm-addstyle-shim/ code / GM_addStyle_shim.js>< / script>< p>此用户脚本将每秒单击一次刷新按钮,< br> / p< div> div某些输入:< p>除非输入输入。 < label> Foo:< input type = text id = Foo>< / label>< br>< br <!-< label for = Bar> Bar:< / label> < textarea id = Bar>< / textarea> ->< / div><按钮类型= button id = some_random_ID title =刷新>刷新< / button>< p id = StatusNd>< / p>  


I'm trying to create a Tampermonkey script that would click the page's "Refresh" button every so often, preferably every minute.

It would be even better if it could pause while you are performing other actions on the site like typing but that's more optional.

Reason for this is that we are using a website at work that needs us to keep track of incoming customer requests in a timely manner but the site only has an integrated refresh button that needs to be clicked manually and doesn't refresh automatically.

There are browser plugins which kinda do what I need but they refresh the whole webpage which causes it to loose important information or settings that have been done before. (this does not happen with the refresh button on the site).

So what i have found was the setInterval and the .click function. What i setup was the following which sometimes worked and sometimes didn't. But every time it did work it wouldn't stop even when disabling Tampermonkey.

// ==UserScript==
// @name         Ticket System - Auto Refresh
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://my*******.***.****mand.com/*
// @grant        none
// ==/UserScript==

setInterval(function () {document.getElementById("buttonOcLMZKwM8KoKda967hf2B0_11").click();}, 10000);

//end

I probably have some significant flaws in what i did above but as i said i have no experience with javascript. Also the time used was to test in order to quickly see if it works or not.

As you probably can see i already got stuck at the refresh part, so the stopping part when typing isn't even remotely done.

I also used

document.getElementById("buttonOcLMZKwM8KoKda967hf2B0_11")

and it is very likely target to fail as the website tends to change this ID when you login again. So i tried to do it by using instead:

document.querySelector('[title="Refresh"]');

but that didn't seem to work at all even though the title of the button is Refresh.

This is the full button HTML on the site:

<button type="button" id="buttonOcLMZKwM8KoKda967hf2B0_11" data-sap-ui="buttonOcLMZKwM8KoKda967hf2B0_11" 
data-sap-automation-id="OcLMZKwM8KoKda967hf2B0" title="Refresh" role="button"
aria-disabled="false" tabindex="0" class="sapUiBtn sapUiBtnIconOnly sapUiBtnLite sapUiBtnS width-button-form sapUiBtnStd">
<img id="buttonOcLMZKwM8KoKda967hf2B0_11-img" src="https://.........TbRefresh.png" 
alt="Refresh" class="sapUiBtnIco"></button>

I would really appreciate any help i can get.

解决方案

To start and stop polling, or interval clicking, etc.; merely:

  1. Store the value of the setInterval() call.
    EG: var myTimer = setInterval (someFunction, 1000);
  2. Pass that value to clearInterval() to stop the loop.
    EG: clearInterval (myTimer);

Of course, the user interface is the hardest part. I like to:

  1. Put a status and control button in the upper-right of the screen.
  2. Bind a keyboard shortcut to be able to toggle the loop without needing the mouse.

The following userscript does all of the above, plus:

  1. Clicks the "Refresh" button on every iteration of the loop.
  2. Stops/Restarts the loop when the control button is clicked.
  3. Stops/Restarts when F9 is pressed (depending on where the focus is).
  4. Stops the loop when one of the form controls is selected or typed into.
  5. Restarts the loop when the "Refresh" button is clicked.

Here is a complete working userscript (It's just the part above the ****** block.).
To see it in action, Run the code snippet.

// ==UserScript==
// @name     _Click button regularly, with start/stop controls
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

//--- Initialize the refresh button loop and controls.
var rfrshBtnSel = 'button[title="Refresh"]';  //  jQuery selector for the refresh
var rfrshTmr    = LoopManager (clickRefreshButton, 1000);  //  1000 ms == 1 second.
var loopStBtn   = LoopButtonManager (rfrshTmr.toggle);

rfrshTmr.setCallbacks (loopStBtn.start, loopStBtn.stop, loopStBtn.error);
rfrshTmr.start ();  //  Start looping the refresh btn click.

$(window).keydown (keyboardShortcutHandler);

//--- On use of certain form controls, stop the refresh timer:
$("body").on (
    "click keydown focus paste scroll", "input, textarea, select", rfrshTmr.stop
);
//--- On click of the refresh button, (re)start the refresh timer:
$("body").on ("click", rfrshBtnSel, rfrshTmr.start);

function clickRefreshButton () {
    var refreshBtn = $(rfrshBtnSel);
    if (refreshBtn.length === 1)  clickNode (refreshBtn);
    else loopStBtn.error ("Refresh button not found!");
}
function keyboardShortcutHandler (zEvent) {
    if (zEvent.which == 120) {  //  On F9, Toggle the Loop state.
        rfrshTmr.toggle ();
        return false;
    }
    return true;
}
function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function LoopManager (callbackFnc, intrvlMillisec, bAutoStart, ...optParams) {
    var _thisInterval = null;
    var _startCB = null, _stopCB = null, _errorCB = null;
    if (bAutoStart)  _start ();

    function _start () {
        if ( ! _thisInterval) {
            _thisInterval = setInterval (callbackFnc, intrvlMillisec, ...optParams);
        }
        if (_startCB)  _startCB ();
    }
    function _stop () {
        clearInterval (_thisInterval);
        _thisInterval = null;
        if (_stopCB)  _stopCB ();
    }
    function _toggle () {
        if (_thisInterval)  _stop ();
        else                _start ();
    }
    function _setCallbacks (startCB, stopCB, errorCB) {
        _startCB = startCB; _stopCB = stopCB; _errorCB = errorCB;
    }
    return {
        start: _start,  stop: _stop,  setCallbacks: _setCallbacks,  toggle: _toggle
    };
}
function LoopButtonManager (clickCB) {
    var _btnNode = $('#tmStartStopBtn');
    if (_btnNode.length === 0) {
        _btnNode = $( `
            <button id="tmStartStopBtn" type="button" class="tmRefreshRunning">
                <span>TBD</span> (F9)
            </button>
        ` ).appendTo ("body");
    }
    var _spanNode = _btnNode.find ("span");

    _btnNode.click (clickCB);

    function _start () {
        setButtonDisplay ("Running", "tmRefreshRunning");
    }
    function _stop () {
        setButtonDisplay ("Stopped", "tmRefreshStopped");
    }
    function _error (errMess) {
        console.error ("TM: " + errMess);
        setButtonDisplay ("See console!", "tmError");
    }
    function setButtonDisplay (btnText, btnClass) {
        _spanNode.text (btnText);
        _btnNode.removeClass ();
        if (btnClass)  _btnNode.addClass (btnClass);
    }
    return { start: _start,  stop: _stop,  error: _error };
}
GM_addStyle ( `
    #tmStartStopBtn {
        position:           absolute;
        top:                0;
        right:              0;
        font-size:          18px;
        margin:             5px;
        opacity:            0.9;
        z-index:            1100;
        padding:            5px 20px;
        color:              black;
        cursor:             pointer;
    }
    .tmRefreshRunning { background: orange; }
    .tmRefreshStopped { background: lime; }
    .tmError { background: red; }
` );

/********************************************************************
******* Everything below this block is simulated target page. *******
******* It's NOT part of the userscript.                      *******
********************************************************************/
$('button[title="Refresh"]').click ( function () {
    $(this).attr ("id", 'spelunk' + Math.random () );
    $("#StatusNd").text ("Refreshed: " + (new Date() + '').replace (/\s*\(.+\)/, "") );
} );

div {
    margin: 0 0 1ex 1em;
    width: 20em;
    padding: 0.5ex 1em 0 1em;
    border: 1px solid darkgreen;
    border-radius: 1ex;
}
label { margin: 0 0 0 2em; }
label[for="Bar"] { display: inline-block;  vertical-align: top; }
button, #StatusNd { margin: 0 0 1ex 2em; }

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://greasyfork.org/scripts/44560-gm-addstyle-shim/code/GM_addStyle_shim.js"></script>
<p>This userscript will click the "Refresh" button every second,<br> unless typing in an input.</p>
<div>Some inputs:<br>
    <label>Foo: <input type="text" id="Foo"></label><br><br>
    <!-- <label for="Bar">Bar: </label>
    <textarea id="Bar"></textarea> -->
</div>
<button type="button" id="some_random_ID" title="Refresh">Refresh</button>
<p id="StatusNd"></p>

这篇关于单击“刷新”用户脚本除非有输入,否则每分钟都按一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆