简体   繁体   中英

Javascript “for” loop crashing page

The goal of this code is to check for a consecutive &, b, u, and =. However, when I input my code through Javascript injection, it crashes the webpage.

Code:

var str = document.URL; //gets URL of webpage
var copied = 0;

//this loop reads the URL character by character and checks if it is an &, b, u, or =. If so, it sets the corresponding variables to 1.
for (var i = 0; i < 1; i++) {
    var res = str.charAt(i);
    if (res == "&") {
        var ampYes = 1;
    } else {
        var ampYes = 0;
    }
    if (res == "b") {
        var bYes = 1;
    } else {
        var bYes = 0;
    }
    if (res == "u") {
        var uYes = 1;
    } else {
        var uYes = 0;
    }
    if (res == "=") {
        var eqYes = 1;
    } else {
        var eqYes = 0;
    }
    alert(res)
}

I presume that the reason it's crashing is due to an error in one of my "if"s. I tested it on a website without an ampersand and it didn't crash. However, on a website with a consecutive &, b, u, and =, it crashed the page.

Don't invent your own wheel. Use url.indexOf("&bu=") > -1 to see if it's in there.

Here is simple solution with regex:

var url = document.URL,
    ampYes, bYes, uYes, eqYes;

ampYes = /\&/gi.test(url) ? 1 : 0;
bYes = /b/gi.test(url) ? 1 : 0;
uYes = /u/gi.test(url) ? 1 : 0;
eqYes = /\=/gi.test(url) ? 1 : 0;

console.log(url, ampYes, bYes, uYes, eqYes);

You can try changing the value of url and testing in here: http://jsfiddle.net/kq82D/

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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