简体   繁体   English

我必须刷新我的Greasemonkey脚本的页面才能运行?

[英]I have to refresh the page for my Greasemonkey script to run?

So I know it's something to do with AJAX, but I've read a few topics and don't quite understand what I have to do. 所以我知道这与AJAX有关,但我已经阅读了一些主题并且不太了解我必须做什么。 Currently everything works fine, but I have to refresh the page for my script to run. 目前一切正常,但我必须刷新页面才能运行我的脚本。 What needs to be done with my code to get it working without refresh? 我的代码需要做些什么才能让它在没有刷新的情况下工作?

// ==UserScript==
// @name    Job Aids
// @description Aid in closing tickets
// @include https://techaccess.ad.qintra.com/WorkJobs/WorkJobs.aspx*
// @namespace   camzilla.net
// @version     1.1.20121128
// ==/UserScript==

var url  = window.location.href.split(".aspx");
var page = url[1].toLowerCase();

if (page == "#finaltest") {
    window.addEventListener ("load", finalResults, false);
} else if (page == "#threetoneslope") {
    window.addEventListener ("load", toneSlopeResults, false);
} else if (page == "#codes") {
    window.addEventListener ("load", closingComments, false);
} else if (page == "#cras") {
    window.addEventListener ("load", crasResults, false);
} else if (page == "#jobinfo") {
    window.addEventListener ("load", addLinks, false);
} else if (page == "") {
    if (getCookie("updater") == null) {
        var d = new Date();

        setCookie("updater", d.getTime(), 1);
        try {
            updateCheck();
        } catch(err) {
            // alert('Update checking failed');
        }
    }

    // setTimeout(promptDispatch, 1000);
}

function addLinks() {
    var mydiv   = document.querySelector('div[data-bind="CurrentJob.addr"]');
    var address = 'https://maps.google.com/maps?q=' + mydiv.textContent + ", UT";
    address.replace(/ /g, '+');  
    var a       = document.createElement("a");
    var txt     = document.createTextNode(mydiv.textContent);
    mydiv.textContent = "";
    a.appendChild(txt);
    a.href   = address;
    a.target = '_blank';
    mydiv.appendChild(a);

    mydiv   = document.querySelector('div[data-bind="CurrentJob.cktid"]');
    address = 'http://acmspjv1.interprise.com/cgi-bin/QC/DSL/dslam6100Int.pl?telephoneNum=';
    address+= mydiv.textContent;
    a       = document.createElement("a");
    txt     = document.createTextNode(mydiv.textContent);
    mydiv.textContent = "";
    a.appendChild(txt);
    a.href   = address;
    a.target = '_blank';
    mydiv.appendChild(a);
}

function updateCheck() {
    try {
        GM_xmlhttpRequest(
        {
            method: 'GET',
            url: 'http://camzilla.net/downloads/jobAids.user.js?v' + getCookie("updater"),
            headers: {'Cache-Control': 'no-cache'},
            onload: function(resp) {
                var local_version, remote_version, rt, script_name;

                rt = resp.responseText;
                remote_version = (/@version\s*(.*?)\s*$/m.exec(rt)[1]);
                local_version  = GM_info.script.version;

                if (remote_version != local_version) {

                    if(confirm(GM_info.script.name+' update v'+remote_version+ ' is available.\nWould you like to install it now?')) {
                        GM_openInTab('http://camzilla.net/downloads/jobAids.user.js');
                    } else {
                        alert('You will be reminded again tomorrow');
                    }
                }
            }
        });
    } catch(err) {
        // do something here
    }
}

function setCookie(c_name, value, exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");

    for (i=0;i<ARRcookies.length;i++) {

        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");

        if (x==c_name) {
            return unescape(y);
        }
    }

    return null;
}

function finalResults() {
    var dc, current, loss, noise, pi, lb;

    dc      = getRandom(51, 49, 2);   
    current = getRandom(37, 29, 2);
    loss    = getRandom(7, 2, 2);
    noise   = getRandom(7, 1, 2);
    pi      = getRandom(67, 60, 2);
    lb      = getRandom(79, 70, 2);

    document.getElementById('finalTestInsightNo').click();

    document.getElementById("finalTestBeforeAcTg").value        = "0.00";
    document.getElementById("finalTestBeforeAcRg").value        = "0.00";
    document.getElementById("finalTestBeforeAcTr").value        = "0.00";
    document.getElementById("finalTestBeforeDcTr").value        = dc;
    document.getElementById("finalTestBeforeDcTg").value        = "0.00";
    document.getElementById("finalTestBeforeDcRg").value        = dc;
    document.getElementById("finalTestBeforeLoopCurrent").value = current;
    document.getElementById("finalTestAfterLoss").value         = loss;
    document.getElementById("finalTestAfterNoise").value        = noise;
    document.getElementById("finalTestAfterPi").value           = pi;
    document.getElementById("finalTestAfterLb").value           = lb;

    document.getElementById("finalTestAfterLb").focus();
    window.scrollTo(0, document.body.scrollHeight-250);

    // Store cookies to be used on cras page if needed
    setCookie("loss", loss, 1);
    setCookie("pi", pi, 1);
    setCookie("current", current, 1);
    setCookie("noise", noise, 1);
    setCookie("lb", lb, 1);
}

function crasResults() {
    document.getElementById("crasCircuitLoss").value    = getCookie("loss");
    document.getElementById("crasPowerInfluence").value = getCookie("pi");
    document.getElementById("crasLineCurrent").value    = getCookie("current");
    document.getElementById("crasCircuitNoise").value   = getCookie("noise");
    document.getElementById("crasBalance").value        = getCookie("lb");

    document.getElementById('crasFoundInF2').click();
}

function toneSlopeResults() {
    var dc = getRandom(51, 49, 2);   

    document.getElementById("ToneSlopeInsightNo").click();
    document.getElementById("ToneSlopeDmarcTaggedYes").click();
    document.getElementById("ToneSlopeClecDtPresentYes").click();

    document.getElementById("ToneSlopeBeforeDcTr").value    = dc;
    document.getElementById("ToneSlopeBeforeDcTg").value    = "0.00";
    document.getElementById("ToneSlopeBeforeDcRg").value    = dc;   
    document.getElementById("ToneSlopeRingbackTr").value    = getRandom(90,85,2);
    document.getElementById("ToneSlopeAfterResistTg").value = getRandom(998,20,0);
    document.getElementById("ToneSlopeAfterResistRg").value = getRandom(998,20,0);
    document.getElementById("ToneSlopeAfterResistTr").value = getRandom(998,20,0);

    document.getElementById("ToneSlopeAfter404").value      = "0.00";
    document.getElementById("ToneSlopeAfter1004").value     = getRandom(7, 3, 2);
    document.getElementById("ToneSlopeAfter2804").value     = "0.00";
    document.getElementById("ToneSlopeAfterNoise").value    = getRandom(7, 1, 2);
    document.getElementById("ToneSlopeAfterLb").value       = getRandom(79, 70, 2);
    document.getElementById("ToneSlopeCotName").value       = "NA";

    document.getElementById("ToneSlopeTn").focus();
}

function closingComments() {
    document.getElementById("flatRateJacks").value = "0";
    document.getElementById("rewiredJacks").value  = "0";

    document.getElementById("tripNo").click();
    document.getElementById("marketMass").click();
    document.getElementById("custTypeRes").click();
    document.getElementById("pairChangeNo").click();
    document.getElementById("tempDropNo").click();
    document.getElementById("goodCbrYes").click();

    document.getElementById("jobCloseComments").focus();
    window.scrollTo(0, 5000);
}

function getRandom(max, min, tenths) {
    var result = min + (Math.random() * (max - min + 1));
    return result.toFixed(tenths);
}

See "addEventListener only working at page refresh?" 请参阅“仅在页面刷新时工作的addEventListener?” for more information and a similar scenario. 了解更多信息和类似情况。

Page elements, that your script expects, are no doubt appearing after the load event has fired. load事件触发后,毫无疑问会出现您的脚本所期望的页面元素。 Additionally, from your comments, it sounds like whole sections of the page are swapped out by AJAX, but the AJAX is polite enough to change the URL hash. 另外,从您的评论中,听起来好像AJAX交换了页面的整个部分,但AJAX足以礼貌地更改URL哈希。 This means you'll want to fire off the hashchange event. 这意味着您将要启动hashchange事件。

Don't use addEventListener ("load"... in this case. Use the waitForKeyElements() utility in conjunction with hashchange . 不要使用addEventListener ("load"...在这种情况下为addEventListener ("load"... 将waitForKeyElements()实用程序hashchange结合使用。

Without refactoring the whole script to use jQuery (which would give clearer and more robust code), replace everything before function addLinks() {... , with: 如果不重构整个脚本以使用jQuery(这将提供更清晰和更健壮的代码),请在function addLinks() {...之前替换所有内容:

// ==UserScript==
// @name        Job Aids
// @description Aid in closing tickets
// @include     https://techaccess.ad.qintra.com/WorkJobs/WorkJobs.aspx*
// @namespace   camzilla.net
// @version     1.1.20121128
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/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.
*/

//-- Pages are "loaded" via AJAX...
window.addEventListener ("hashchange", fireOnNewPage,  false);

waitForKeyElements ("#crasCircuitLoss",                 crasResults);
waitForKeyElements ("#finalTestInsightNo",              finalResults);
waitForKeyElements ("#flatRateJacks",                   closingComments);
waitForKeyElements ("#ToneSlopeInsightNo",              toneSlopeResults);
waitForKeyElements ("div[data-bind="CurrentJob.addr"]", addLinks);

function fireOnNewPage () {
    switch (location.hash.toLowerCase() ) {
        case "#finaltest":
        case "#threetoneslope":
        case "#codes":
        case "#cras":
        case "#jobinfo":
            //-- No action needed, waitForKeyElements() handles this.
        break;
        default:
            if (getCookie("updater") == null) {
                var d = new Date();

                setCookie("updater", d.getTime(), 1);
                try {
                    updateCheck();
                } catch(err) {
                    // alert('Update checking failed');
                }
            }
        break;
    }
}
fireOnNewPage ();   //-- Initial run on initial, full page load.

check out some ajax examples across the net by searching. 通过搜索查看网上的一些ajax示例。 for example: http://www.w3schools.com/ajax/ajax_examples.asp 例如: http//www.w3schools.com/ajax/ajax_examples.asp

AJAX, or (A)synchronous (J)avascript (A)nd (X)ML (which interestingly enough tends to use JSON more these days), is a system in which Javascript uses a browser object to communicate with a remote server. AJAX,或(A)同步(J)avascript(A)nd(X)ML(有趣的是,这些天有时候更多地使用JSON),是一个Javascript使用浏览器对象与远程服务器通信的系统。 The general use case of this is to be able to update a client's interface without needing to go to another page. 这种情况的一般用例是能够更新客户端的界面而无需转到另一个页面。 Before we begin though, a few words of caution. 在我们开始之前,请注意几句。

Ajax is not recommended for login authentication and posting forms Users can turn off Javascript, or may be restricted from running Javascript due to IT policies 建议不要将Ajax用于登录身份验证和发布表单用户可以关闭Javascript,也可能因为IT策略而无法运行Javascript

With this in mind it is advised that you do not use AJAX as the sole solution for critical user functionality! 考虑到这一点,建议您不要将AJAX用作关键用户功能的唯一解决方案! Always have a fallback! 总是有一个后备! Note: This community wiki post uses JQuery to show the example AJAX calls. 注意:这个社区wiki帖子使用JQuery来显示示例AJAX调用。 It's recommended for newcomers as it hides the browser compatibility issues of making AJAX calls. 它建议新手使用,因为它隐藏了制作AJAX调用的浏览器兼容性问题。 Please check the JQuery website for more information on JQuery. 有关JQuery的更多信息,请查看JQuery网站。

Note: The examples use communication with a PHP server, but any server side language will work. 注意:这些示例使用与PHP服务器的通信,但任何服务器端语言都可以使用。

AJAX Callbacks AJAX回调

function makeAjaxCall() {
  $.ajax({
    url: 'ajax/test.html',
    success: function(data) {
      alert('Horray the AJAX call succeeded!');
    },
    error: function(xhr, error) {
      alert('Holy errors batman!');
    }
  });
}

The Nature of AJAX Calls AJAX调用的本质

AJAX calls can be either Asynchronous or Synchronous. AJAX调用可以是异步调用,也可以是同步调用。 Asynchronous means that the browser will make the AJAX request and continue doing other things. 异步意味着浏览器将发出AJAX请求并继续执行其他操作。 Synchronous means the browser will stop what it's doing until the AJAX call completes. 同步意味着浏览器将停止正在进行的操作,直到AJAX调用完成。 Here is an example of the differences in the two code wise: 以下是两个代码方面的差异示例:

// An asynchronous call
// This is the default
$.ajax({
  url: '/server.php',
  success: function(data) {
    alert('Horray the AJAX call succeeded!');
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});
// This will get called right away
myFunction();
Now for a synchronous call:

// A synchronous call
$.ajax({
  url: '/server.php',
  async: false, // set the property here
  success: function(data) {
    alert('Horray the AJAX call succeeded!');
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM