【问题标题】:How to pass arguments into Javascript functions on websites via console如何通过控制台将参数传递给网站上的 Javascript 函数
【发布时间】:2019-07-22 01:14:48
【问题描述】:

我正在尝试绕过我目前正在学习的课程中的计时器,除非计时器已达到 0,否则我无法前进到下一页。我正在使用 TamperMonkey 将函数的值设置为值将允许我让计时器达到 0 但无济于事。如何通过控制台或 tampermonkey 将参数传递给 Javascript 中的函数,以便将计时器设置为 0 并在每个页面中前进?我主要用 Python 编程,这是我第一次尝试用 Javascript 编码。

使用最新版本的 Google Chrome 和 Tampermonkey。我当前的 Tampermonkey 脚本使计时器无效并将其设置为空值 (----)

(function() {
    'use strict';

    // Your code here...
    window.seconds = 0;
    var scriptContent = "UpdateTimer('TimeRemainingClock', 0, 'DOWN')";
var script = document.createElement('script')
script.appendChild(document.createTextNode(scriptContent));
document.getElementsByTagName('head')[0].appendChild(script);
})();

什么都没有。

网站的JS代码是:


var pageLoaded = 0; 
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;

function UpdateElapsedTimer()
{
    var s = secondsElapsed + (GetTickDiff()/1000);  
    UpdateTimer('TotalTimeClock', s, 'UP');
}

function GetTickDiff()
{
    var d = new Date();
    var tickDiff = d.getTime() - startTicks;
    return tickDiff;
}

function UpdateRemainingTimer()
{

    var s = secondsRemaining - (GetTickDiff()/1000);

    estimatedSecondsRemaining = s;

    if (s < 0) s = 0;

    UpdateTimer('TimeRemainingClock', s, 'DOWN');
}

function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){


    //check to see if we can run this code yet
    if(document.getElementById && document.getElementById(ClockID) != null){

        //declare vars
        var _Seconds = 0;
        var _Minutes = 0;
        var _Hours = 0;

        //Format Seconds
        _Seconds = Math.floor(ElapsedSeconds % 60);
        if(_Seconds <= 9) {
            _Seconds = "0"+_Seconds;
        }

        //Format minutes
        _Minutes = Math.floor(ElapsedSeconds/60 % 60);
        if(_Minutes <= 9) {
            _Minutes = "0"+_Minutes;
        }

        //Format hours
        _Hours = Math.floor(ElapsedSeconds/3600);
        if(_Hours <= 9){
            _Hours = "0"+_Hours;
        }

        document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;

        if (timerStatus != 'active')
        {   
            setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);  
            return;
        }

        if(ElapsedSeconds > 0 || ClockDirection == "UP"){

            if(ClockDirection == "UP")
            {
                ElapsedSeconds = ElapsedSeconds + 1;
            }
            else
            {
                ElapsedSeconds = ElapsedSeconds - 1;
            }

            //setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);            
        }
        else{
            //Timer has hit zero. Lets make sure the next buttons are visible.
            $('#next_top').show();
            $('#next_bot').show();
        }   
    }
    else if(!pageLoaded) //call function again in 100ms
    {
        //setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
    }

使用 TamperMonkey 脚本时,输出为: TimerUtils.01.js:262 未捕获类型错误:UpdateTimer 不是函数 在 UpdateElapsedTimer (VM27051 TimerUtils.01.js:262) 在 UpdateBothTimers (VM27051 TimerUtils.01.js:200) 在:1:1

我了解范围的概念,但不了解我的输出应该是什么。

感谢任何帮助。非常感谢!

【问题讨论】:

  • 在我看来 UpdateTimer 为空或在调用 UpdateElapsedTime 之前被重新定义为另一个值。您是在 UpdateElapsedTimer 之前调用 UpdateTimer 吗?如果您乱序调用,也许有一些代码会重新定义 UpdateTimer。我认为答案在 TimerUtils.01.js 中,你能分享一下吗?

标签: javascript console


【解决方案1】:

var pageLoaded = 0; 
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;

$(document).ready(function() {
    setInterval('AutoSave()', 120000);
    intervalIdUpdateBothTimers = setInterval('UpdateBothTimers()', 1000);

    if (timerStatus == 'pending') {
    
        var totaltimeclock = document.getElementById('TotalTimeClock');
        if (totaltimeclock != null) {
            document.getElementById('TotalTimeClock').innerHTML = '-- \: -- \: --';
        }

        var timeremainingclock = document.getElementById('TimeRemainingClock');
        if (timeremainingclock != null) {
            document.getElementById('TimeRemainingClock').innerHTML = '-- \: -- \: --';
        }

        StartTimer();
    }

});

function loaded(i,f) {
    if (document.getElementById && document.getElementById(i) != null) 
    {
        f(); 
    }
    else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}

function SuspendTimer() {
    UpdateBothTimers();
    
    if (timerStatus == 'active') {
        var data = "s=2&cp=" + this.location.pathname + "&nlg=" + GetNonLinearGuid();
        timerStatus = 'suspended';

        $.ajax({
            type: "POST",
            url: "/Courses/ajax/CourseData.aspx",
            data: data,
            success: displayTime,
            async: false
        });

        clearInterval(intervalIdUpdateBothTimers);
    }
    
}

function AutoSave()
{
    if (timerStatus == 'active')
    {
        SaveTime();
    }
}

function SaveTime()
{
    var data = '';
    if (typeof window.IsScormPage === 'undefined')
    {
        data = "cp=" + this.location.pathname + "&sp=false";
    }
    else
    {
        data = "cp=" + this.location.pathname + "&sp=true";
    }

    data += "&nlg=" + GetNonLinearGuid();

    $.ajax({
        type: "POST",
        url: "/Courses/ajax/CourseData.aspx",
        data: data,
        success: displayTime,
        async: false
    });  
}

function StartTimer()
{
    timerStatus = 'active';

    SetNonLinearGuid();
    SaveTime();
}

// Sets the nonLinearGuid with the one in the DOM
// the GUID was generated in the server side and
// passed it to the client side (DOM)
function SetNonLinearGuid()
{
    var $nonLinearGuid = $("#nonLinearGuid");

    if ($nonLinearGuid === undefined)
    {
        $nonLinearGuid = $("input[name=nonLinearGuid]");
    }

    if ($nonLinearGuid.length)
    {
        nonLinearGuid = $nonLinearGuid.val() || null;
        window.nonLinearGuid = window.nonLinearGuid || nonLinearGuid;
    }
}

function GetNonLinearGuid() {
    var nlg = (window.NonLinearGuid || nonLinearGuid),
        admin = getQueryStringByName("admin", parent.window.location.href) || "";

    if (admin.toLowerCase() == "d3v") {
        printNonLinearGuid(nlg);
    }

    return nlg;
}

function getQueryStringByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function displayTime(result)
{
    
    if (result.isOk == false)
    {
        alert(result.message);
    }
    else
    {   
        var d = new Date();
        startTicks = d.getTime();
        
        secondsRemaining = parseInt($(result).find("SecondsRemaining").text());
        secondsElapsed = parseInt($(result).find("SecondsElapsed").text());
        redirectUrl = $(result).find("RedirectUrl").text();

        var suspendTimer = $(result).find("SuspendTimer").text();
        var dataNonLinearGuid = "?nlg=" + GetNonLinearGuid();
        
        if (redirectUrl != "") {
            location.href = redirectUrl;
        }
        
        isError = $(result).find("Error").text();
        
        if (isError == "true")
        {
            errorCount++;
            
            if (errorCount > 3)
            {
                logout();
            }
        }

        isOverworked = $(result).find("IsOverworked").text();
        if (isOverworked == "true") 
        {
            location.href = "/Courses/MyAccountNonLinear.aspx" + dataNonLinearGuid;
        }

        if (suspendTimer.length > 0) {
            if ($.trim(suspendTimer).toLowerCase() == "true") {
                SuspendTimer();
            }
        }       
    }
}

function logout()
{
    window.top.location.href = "/Courses/loggedout.aspx";
}

function UpdateBothTimers() {
    
    if (timerStatus != 'active') return;
    
    if (secondsElapsed >= 0)
    {    
        UpdateElapsedTimer();
        //secondsElapsed++;
    }

    if (secondsRemaining >= 0) {
        UpdateRemainingTimer();
    }

    if (estimatedSecondsRemaining <= 0 && zeroTimeCounter == 0) {
        zeroTimeCounter++;     
        SaveTime();
    }
}
var lang;
function qt(m,lng) {
    
    $('#timeRemaining').css('display', 'none');
    setTimeout("$('#EOMQuiz').submit();", m * 1000);
    lang = lng;
    setTimeout('updateQ('+ m +')', 1000);
}

function updateQ(m) {
   
    --m;
    var text;
    if (lang == 'es') {
        text = 'Entregar - ' + m + ' segundos restantes para completar la prueba';
    }
    else {
        text = 'Submit - ' + m + ' seconds remaining to complete the quiz';
    }
   
    if (m > 0) {
       
        setTimeout('updateQ('+m+')', 990);
    }
    else
    {
        $('#eomsubmitDiv').css('background-color', '#FF0000');
       text ='Submitting... Please Wait.';    
    }
   
    if (m <= 10 && m > 0)
    {
        if (m % 2 == 0)
        {
            $('#eomsubmitDiv').css('background-color', '#FFFF00');
        }
        else
        {
            $('#eomsubmitDiv').css('background-color', '#FFFFAA');        
        }
           
    }
    
    $('#eomsubmit').attr('value', text);
}

function UpdateElapsedTimer()
{
    var s = secondsElapsed + (GetTickDiff()/1000);  
    UpdateTimer('TotalTimeClock', s, 'UP');
}

function GetTickDiff()
{
    var d = new Date();
    var tickDiff = d.getTime() - startTicks;
    return tickDiff;
}

function UpdateRemainingTimer()
{
    
    var s = secondsRemaining - (GetTickDiff()/1000);

    estimatedSecondsRemaining = s;
    
    if (s < 0) s = 0;
    
    UpdateTimer('TimeRemainingClock', s, 'DOWN');
}

function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){

    
    //check to see if we can run this code yet
    if(document.getElementById && document.getElementById(ClockID) != null){

        //declare vars
        var _Seconds = 0;
        var _Minutes = 0;
        var _Hours = 0;
        
        //Format Seconds
        _Seconds = Math.floor(ElapsedSeconds % 60);
        if(_Seconds <= 9) {
            _Seconds = "0"+_Seconds;
        }
        
        //Format minutes
        _Minutes = Math.floor(ElapsedSeconds/60 % 60);
        if(_Minutes <= 9) {
            _Minutes = "0"+_Minutes;
        }
        
        //Format hours
        _Hours = Math.floor(ElapsedSeconds/3600);
        if(_Hours <= 9){
            _Hours = "0"+_Hours;
        }
        
        document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;
        
        if (timerStatus != 'active')
        {   
            setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);  
            return;
        }

        if(ElapsedSeconds > 0 || ClockDirection == "UP"){
        
            if(ClockDirection == "UP")
            {
                ElapsedSeconds = ElapsedSeconds + 1;
            }
            else
            {
                ElapsedSeconds = ElapsedSeconds - 1;
            }
            
            //setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);            
        }
        else{
            //Timer has hit zero. Lets make sure the next buttons are visible.
            $('#next_top').show();
            $('#next_bot').show();
        }   
    }
    else if(!pageLoaded) //call function again in 100ms
    {
        //setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
    }
}   


function DisplayNextButtons(){
    $('#next_top').show();
    $('#next_bot').show();
}

function hideNextButtons(){
    $('#next_top').hide();
    $('#next_bot').hide();
}

【讨论】:

  • 最好在你的答案中解释问题是什么以及你是如何解决的。只是“撞”不是很有帮助。
猜你喜欢
  • 1970-01-01
  • 2014-08-27
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 2010-11-03
  • 1970-01-01
  • 2020-04-03
相关资源
最近更新 更多