0

I'm writing a script that will listen for form submits then preventDefault, gather all the inputs, post them to a site, then submit the form. Here's my tampermonkey so far:

// ==UserScript==
// @name         Dealership Input Listener
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.legacytoyota.com/*
// @match        https://www.volumechevrolet.com/*
// @match        https://www.downtownnashvillenissan.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    document.onreadystatechange = function(){
        if(document.readyState === 'complete'){
            alert("working");
        if (typeof jquery == 'undefined') {
            var headTag = document.getElementsByTagName("head")[0];
            var jqTag = document.createElement('script');
            jqTag.type = 'text/javascript';
            jqTag.src = '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js';
            jqTag.onload = myJqueryCode();
            headTag.appendChild(jqTag);
        } else 
            myJqueryCode();
    }
};

function myJqueryCode() {
    alert("working2");
    if (typeof $().modal == 'undefined') {
        alert("Installing bootstrap");
        // Add Bootstrap CSS & JS
        var head  = document.getElementsByTagName('head')[0],
            link  = document.createElement('link');
        link.id   = 'bootstrapCss';
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = '//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css';
        link.media = 'all';
        head.appendChild(link);
        // ---------------------- //
        var head = document.getElementsByTagName('head')[0],
            script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = '//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js';
        head.appendChild(script);
    } else {
        console.log(typeof $().modal);
        alert("bootstrap found");
    }

    var loadingTimer = 0,
        continueWaiting = true;
    while (continueWaiting) {
        if (loadingTimer === 10000 || (typeof jQuery != 'undefined' && typeof $().modal != 'undefined')) {
            continueWaiting = false;
            setControllers();
        }
        loadingTimer++;
    }
}

function setUserInfo(hlxValues, formObj) {
    $.get("//freegeoip.net/json/", function(data) {
        hlxValues['ip'] = data.ip;
        hlxValues['city'] = data.city;
        hlxValues['latitude'] = data.latitude;
        hlxValues['longitude'] = data.longitude;
        hlxValues['state'] = data.region_code;
        hlxValues['ZIP'] = data.zip_code;

        submitToHelix(hlxValues, formObj);
    });
}

function setControllers() {
    alert("in setControllers");
    var hlxValues = new Array();
    hlxValues['guid'] = guid();
    hlxValues['url'] = window.location.href;
    hlxValues['form'] = new Array();

    $('form').submit(function(e) {
        alert("form submitted");
        var thisID = this.id;
        e.preventDefault();

        var myForm = document.getElementById(thisID);
        for (var i = 0; i < myForm.elements.length; i++) {
            if (myForm.elements[i].getAttribute("type") != "submit") {
                var fieldIdOrName = '',
                    fieldValue = '';
                if (isset(myForm.elements[i].id) && myForm.elements[i].id.length > 0)
                    fieldIdOrName = myForm.elements[i].id;
                else
                    fieldIdOrName = myForm.elements[i].getAttribute("name");

                fieldValue = myForm.elements[i].value;
                hlxValues['form'][fieldIdOrName] = fieldValue;
            }
        }
        setUserInfo(hlxValues, this);
    });
}

function submitToHelix(hlxValues, formObj) {
    console.log(hlxValues);
    alert("About to send form to helix");
    $.post("//formfills.drivehelix.com", { form: json_encode(hlxValues) }, function(data) {
        alert("form sent to helix");
        //$(formObj).submit();
    });
}

function isset(){var r=arguments,t=r.length,n=0;if(0===t)throw new Error("Empty isset");for(;n!==t;){if(void 0===r[n]||null===r[n])return!1;n++}return!0}
function guid(){function r(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return r()+r()+"-"+r()+"-"+r()+"-"+r()+"-"+r()+r()+r()}
function json_encode(n){var e,t=this.window.JSON;try{if("object"==typeof t&&"function"==typeof t.stringify){if(void 0===(e=t.stringify(n)))throw new SyntaxError("json_encode");return e}var r=function(n){var e=/[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,t={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return e.lastIndex=0,e.test(n)?'"'+n.replace(e,function(n){var e=t[n];return"string"==typeof e?e:"\\u"+("0000"+n.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+n+'"'},o=function(n,e){var t="",u=0,i="",f="",c=0,s=t,a=[],l=e[n];switch(l&&"object"==typeof l&&"function"==typeof l.toJSON&&(l=l.toJSON(n)),typeof l){case"string":return r(l);case"number":return isFinite(l)?String(l):"null";case"boolean":case"null":return String(l);case"object":if(!l)return"null";if(this.PHPJS_Resource&&l instanceof this.PHPJS_Resource||window.PHPJS_Resource&&l instanceof window.PHPJS_Resource)throw new SyntaxError("json_encode");if(t+="    ",a=[],"[object Array]"===Object.prototype.toString.apply(l)){for(c=l.length,u=0;u<c;u+=1)a[u]=o(u,l)||"null";return f=0===a.length?"[]":t?"[\n"+t+a.join(",\n"+t)+"\n"+s+"]":"["+a.join(",")+"]",t=s,f}for(i in l)Object.hasOwnProperty.call(l,i)&&(f=o(i,l))&&a.push(r(i)+(t?": ":":")+f);return f=0===a.length?"{}":t?"{\n"+t+a.join(",\n"+t)+"\n"+s+"}":"{"+a.join(",")+"}",t=s,f;case"undefined":case"function":default:throw new SyntaxError("json_encode")}};return o("",{"":n})}catch(n){if(!(n instanceof SyntaxError))throw new Error("Unexpected error type in json_encode()");return this.php_js=this.php_js||{},this.php_js.last_error_json=4,null}}
})();

As you can see, I'm checking to see if jQuery exists. If it doesn't I'm injecting it. I'm then checking if $().modal has a typeof of function... if not - i'm injecting it.

However, when I hit the site and the script runs, the console is showing:

searchnew.aspx:1232 Uncaught TypeError: jQuery(...).modal is not a function

If I go into the console and do "typeof $().modal" I get function, so I'm not sure what i'm getting this error message. Any thoughts?

Brds
  • 1,035
  • 3
  • 17
  • 37
  • The code doesn't wait for the injected scripts to load. – JJJ Aug 07 '17 at 20:49
  • I put a while loop in there that loops until both typeof jQuery and typeof $().modal are not undefined then calls another function. That new function still results in "jQuery(...).modal is not defined" – Brds Aug 07 '17 at 21:15
  • I don't see any loop in the code. – JJJ Aug 07 '17 at 21:16
  • Updated code.... – Brds Aug 07 '17 at 21:55
  • You can't use a loop to wait for a script to load; the loop blocks script execution so the browser never gets the chance to even start loading the other scripts. And, even if you could, a cut-off point of 10,000 iterations is way too short: any modern computer makes 10,000 loops in less than a millisecond. – JJJ Aug 08 '17 at 05:14
  • Possible duplicate of [In JavaScript how to wait for dynamically injected scripts are loaded before start using them?](https://stackoverflow.com/questions/36287285/in-javascript-how-to-wait-for-dynamically-injected-scripts-are-loaded-before-sta) – JJJ Aug 08 '17 at 05:16

0 Answers0