js getting remote div content into variable - javascript

I have a webpage where I put status of my webservice task. It looks like this:
<body>
<div id="size">
<c:out value="${size}"/>
</div>
<div id="isRunning">
<c:out value="${isRunning}"/>
</div>
<div id="intIsRunning">
<c:out value="${intIsRunning}"/>
</div>
<div id="status">
<c:out value="${status}"/>
</div>
</body>
after rendering I get this:
<body>
<div id="size">
100
</div>
<div id="isRunning">
false
</div>
<div id="intIsRunning">
0
</div>
<div id="status">
0
</div>
</body>
size is the size of a job and can be any int value. isRunning is true or false and intIsRunning is 1 or 0. status is percentage completion of the job.
I'd like to be able to get content of those ids and put them into js variables on my other web page however I'm not js aficionado myself.
For now I have this:
$(document).ready(function() {
$('.progress .bar').progressbar();
var fetch = setInterval(loadStatus, 500);
var isRunning;
function loadStatus() {
$.get('/status #intIsRunning', function (data) {
console.log(data);
console.log("!");
console.log("--->("+$(data).index("#status")+")");
});
isRunning = 0;
console.log(">>" + isRunning);
// console.log($('.progress .bar').prop(['data-transitiongoal']));
// $('.progress .bar').prop(['data-transitiongoal']).load('/status #status');
// $('.progress .bar [data-transitiongoal]').load('/status #status');
// $('.bar').attr('data-transitiongoal', i.toString());
// console.log("progress: "+progress);
if (isRunning == 0) {
clearInterval(fetch);
}
}
});
This script should query my status page for aforementioned values and put status into my progress bar as long as running is true. If running is false this script should stop but right now I can't extract those variables. Could anyone provide help?
EDIT:
I got it to work that way:
<script type = text/javascript>
$(document).ready(function () {
$('.progress .bar').progressbar();
var fetch = setInterval(loadStatus, 500);
var isRunning;
var status;
function loadStatus() {
$.get('/status', function (data) {
var remoteContent = $(data);
isRunning = parseInt($(remoteContent[11]).html());
status = parseInt($(remoteContent[13]).html());
if (isRunning == 0) {
status = 100;
clearInterval(fetch);
$("#progBar").hide();
$("#buttonDiv").hide();
$("#succesMessage").show();
//location.reload();
}
$('.progress .bar').attr("data-transitiongoal", status.toString()).progressbar();
console.log("isRunning: " + isRunning + " status: " + status + "%");
});
}}
);
</script>
I'll check posted answer later this week.

What if you try something like this:
$(document).ready(function() {
var fetch = setInterval(loadStatus, 500);
$('.progress .bar').progressbar();
function loadStatus() {
$.get('/status', function (data) {
var $data = $(data), //turn ajax response (string) into JQuery collection
isRunning = $data.find('#isRunning').text(),
intIsRunning = $data.find('#isRunning').text(),
size = $data.find('#isRunning').text(),
status = $data.find('#isRunning').text();
//Do something with the variables
if (isRunning == 0) {
clearInterval(fetch);
}
});
}
});
Note that the variables will all be strings. You can cast to a number using status = parseInt(status, 10) or to boolean using isRunning = (isRunning != 'false'), for example. Note though that with javascript's implicit type conversions this is often not necessary.

Related

Ajax successfully fetching URL but not updating page, instead get [object HTMLDivElement]

So I'm trying to make a next/prev buttons using javascript, and have used a DynamicPage script to help test this. I've only changed the start of the URL variable in pagenumber.js however will essentially give the same message. I want to be able to click next/prev, which will then update the main body with another page of content via AJAX.
I checked the console and no errors are present, and opening the Network tab of the inspector shows the URL which I'm aiming to open is actually being loaded, however the container just displays
[object HTMLDivElement]
I've never properly used AJAX before so chances are I'm doing something wrong. If somebody could please point me in the right direction I'd be much appreciative!
Thanks.
My pagenumber.js is as follows:
var i = 0;
function loadPage(i) {
/* IMPORTANT: ENSURE var url equals the exact domain and location of inductions OR it will fail */
var url = "https://example.com/inductions/induction-page-" + i + ".html";
fetch(url).then(content => {
document.getElementById("guts").innerHTML = guts;
document.getElementById("display").innerHTML = i;
});
}
function incPage() {
i++;
if (i > 10) i = 1;
loadPage(i);
}
function decPage() {
i--;
if (i < 1) i = 10;
loadPage(i);
}
My main HTML is as follows:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript' src='js/jquery.ba-hashchange.min.js'></script>
<script type='text/javascript' src='js/dynamicpage.js'></script>
<script type='text/javascript' src='js/pagenumber.js'></script>
<div id="container">
<div id="page-wrap">
<header>
<a id="decc"><input type="button" value="Previous" id="dec" onclick="decPage();"/></a>
<a id="incc"><input type="button" value="Next" id="inc" onclick="incPage();"/></a>
Page: <label id="display"></label>
</header>
<section id="main-content">
<div id="guts">
<h3>Initial Induction Page</h3>
<p>This is initial content on loading main HTML doc. This content will change when hitting next/prev buttons.</p>
</div>
</section>
</div>
Also, the dynamicpage.js is as follows:
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
console.log(window.location.hash);
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
fetch returns a Response object. This object tells you how the server responded and allows you to extract the data you received in multiple ways. Since you use innerHTML to set the newly downloaded data you'll need to use the text() method of the response. This will return a promise that when finished presents the result in a string. And you should use that result to set your innerHTML with on the guts element.
If the content returned from the response is a full HTML page and you need a part from it, use the DOMParser API, parse the string to HTML and use querySelector to select the element which you need to content from.
var i = 0;
var guts = document.getElementById("guts");
var display = document.getElementById("display");
function loadPage(i) {
/* IMPORTANT: ENSURE var url equals the exact domain and location of inductions OR it will fail */
let url = "https://example.com/inductions/induction-page-" + i + ".html";
fetch(url).then(response => {
if (response.status === 200) {
return response.text();
}
throw new Error(`Error occurred fetching ${url}. Status: ${response.status});
}).then(getGutsFromContent).then(content => {
guts.innerHTML = content;
display.textContent = i;
});
}
function getGutsFromContent(content) {
const parser = new DOMParser();
const doc = parser.parseFromString(content, 'text/html');
const guts = doc.querySelector('#guts');
if (guts !== null) {
return guts.innerHTML;
}
}

Click "submit", send data, but keep the page from redirecting to the new URL

What my script does:
I open https://mylink.com/#script
The script in my chrome extension checks for the #script in the URL and calls a function
The function clicks some checkboxes and then a "submit" button
After 3 seconds the script refreshes the website with the hashtag to create an infinite loop
Problem:
The data from the checkboxes/submit need to go through to the server - that's why I have to wait some time before refreshing. The 3 seconds seem to be enough for that.
Sometimes the website takes 15 seconds until it redirects me to the new site after submitting, but sometimes it's lightning fast and opens the new website before the 3 seconds before the reload have passed - since the opened website doesn't have the #script, my loop stops working.
What I need help with:
How long does it take to send the information from the form so they get through to the server? I know that I don't have to wait for the server's answer and the redirection to the new page, but I think I can't refresh instantly.
Is there a way to detect at which point the new site will be opened so the script could call a function before that happens and redirect to the URL with the hashtag? Or even better: Detect the moment when the information is completely sent from the client side and then instantly refresh.
I would like to keep the time the whole loop needs as short as possible!
Code for understanding:
The submit form on the website:
<form action="/withdraw-request" method="post">
<input type="hidden" name="_csrf" value="YEZknGzr-HW1ThkFrf9bO1M_IuQRJSVk-W6M">
<div id="items">...contains checkboxes...</div>
<input class="button right blue" type="submit" value="Withdraw selected items">
</form>
My content.js (in the chrome extension):
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
if(window.location.hash=="#script") {
var tradestatus = document.getElementsByTagName("td");
console.log("Offer-status: " + tradestatus[8].innerHTML);
var oneKeyOnly = true;
function checkItem() {
var itemsArray = ["Apples", "Bananas", "Melons", ];
var matchingItems = [];
var x = document.getElementsByClassName("item");
for(var y = 0; y < x.length; y++){
if(itemsArray.indexOf(x[y].getAttribute("data-name")) >= 0){
var id = x[y].getElementsByClassName("item-checkbox")[0].getAttribute("id");
matchingItems.push(id);
}
}
return matchingItems;
}
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'submit' && buttons[i].value == val)
{
buttons[i].click();
console.log("Trying to withdraw!");
break;
}
}
}
var result = checkItem();
var lengthOfArray = result.length - 1;
if (oneKeyOnly == true) {
var rand = randomIntFromInterval(0,lengthOfArray);
document.getElementById(result[rand]).checked = true
console.log("Found: " + result[rand]);
}
else {
for(index=0, len = result.length; index < len; ++index) {
document.getElementById(result[index]).checked = true
keynr = index + 1;
console.log("Found " + result.length + " fruits - Selected Nr. " + keynr + "!");
}
}
clickButton("Withdraw selected items");
unloadready = true;
setTimeout((function(){ location.reload(true) }), 3000);
}
}
}, 10);
});
Withdraw.js:
Pastebin: http://pastebin.com/9q72Ti2b
It gets called from somewhere. I can see it in the "network" tab next to the chrome console.
Edit_1:
I tried to use google for a while now and found an ajax documentation and a piece of code that I tried to modify so it would work for me. There is still some really basic stuff that I don't understand.
The code:
$('#submit').click(function()
{
$.ajax({
url: withdraw-request,
type:'POST',
data:
{
items,
_csrf
},
success: function(msg)
{
alert('Success!');
location.reload(true);
}
});
});
Here is the form again from that website with one of the checkboxes added.
<form action="/withdraw-request" method="post">
<input type="hidden" name="_csrf" value="YEZknGzr-HW1ThkFrf9bO1M_IuQRJSVk-W6M">
<input type="checkbox" name="items" value="34155017" class="item-checkbox" id="item-34155017" data-price="562500">
<input class="button right blue" type="submit" value="Withdraw selected items">
</form>
So if I understand it right, then the website is using POST to send "_csrf" and "items" to "withdraw-request" (added the names to "data" in the code).
Why is there nothing like ".php" on "withdraw-request"?
How can I call this code if the form doesn't have a name for its own?
How can I add something like "onClick" or "onSubmit" to a website that is not my own and where I can't change the actual code? Solved that one myself!
document.getElementsByTagName("FORM")[1].setAttribute("onsubmit", "specialFunction()");
Edit_2:
Kind of made it work:
I added this to my 'content.js' to add a name to the form and an ajax function:
var formAdd = document.getElementsByTagName('FORM');
formAdd[1].setAttribute("id", "submitthisform");
var $form = $("#submitthisform");
// register handler for submit first
$form.submit(function (event) {
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize()
})
.done(function (data) {
})
.fail(function (r, s, e) {
});
event.preventDefault();
});
I can call this by $form.submit();. It seems to work, but it still redirects to the new page. What am I doing wrong here?

read class and apply css with javascript or jquery

I wanna apply css with short class name with number.
for example,
if I use class name mt-100, it means margin-top:100px.
if I use class name mr-200, it means margin-right:200px.
if I use class name mt-100 mr-200, it means margin-top:100px and margin-right:200px.
if I use class name pt-100 mt-100 mr-200, it means padding-top:100px and margin-top:100px and margin-right:200px.
I try to make it but it does not work.
I do not want to make every class in css like this --> .mt-100{margin-top:100}
could you help me how to do make this?
thank you in advance.
let me show you my code below,
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function classStartsWith(str) {
return $('div').map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].substr(0, str.length) == str) return e;
}
}).get();
}
function classEndWith(str) {
return $('div').map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].indexOf('mt-') || classes[i].indexOf('mb-') || classes [i].indexOf('mr-') || classes[i].indexOf('ml-') || classes[i].indexOf('pt-') || classes[i].indexOf('pb-') || classes[i].indexOf('pr-') || classes[i].indexOf('pl-'))
{
var ct = classes[i].split('-');
var cts = ct[1];
}
if (classes[i].substr(0, str.length) == str) return e,cts;
}
}).get();
}
$(document).ready(function(){
$(classStartsWith('mt-')).each(function(){
$(this).css('margin-top', classEndWith('mt-')+'px');
});
$(classStartsWith('mb-')).each(function(){
$(this).css('margin-bottom', classEndWith('mb-')+'px');
});
$(classStartsWith('mr-')).each(function(){
$(this).css('margin-right', classEndWith('mr-')+'px');
});
$(classStartsWith('ml-')).each(function(){
$(this).css('margin-left', classEndWith('ml-')+'px');
});
$(classStartsWith('pt-')).each(function(){
$(this).css('padding-top', classEndWith('pt-')+'px');
});
$(classStartsWith('pb-')).each(function(){
$(this).css('padding-bottom', classEndWith('pb-')+'px');
});
$(classStartsWith('pr-')).each(function(){
$(this).css('padding-right', classEndWith('pr-')+'px');
});
$(classStartsWith('pl-')).each(function(){
$(this).css('padding-left', classEndWith('pl-')+'px');
});
});
</script>
</head>
<body>
<div class="mt-100 mb-200" style="width:300px;height:300px;border:1px solid red">
aaaa
</div>
<div class="pt-200 mb-200" style="width:300px;height:300px;border:1px solid red">
bbb
</div>
<div class="pr-300 ml-300 mt300" style="width:300px;height:300px;border:1px solid red">
ccc
</div>
<div class="pl-200 mt200" style="width:300px;height:300px;border:1px solid red">
ddd
</div>
</body>
The way you handle it now presents way too much overhead for this kind of task.
I recommend you to learn more about using the data attribute on your HTML tags. These attributes allow you to define tag specific settings which you can easily read with jQuery and make it respond to the data.
Example:
<div class="my-div-class" data-mt="100" data-mb="200">...</div>
<div class="my-div-class" data-pt="200" data-mb="200">...</div>
<script>
$(function() {
// Walk through each element with this class
$('.my-div-class').each(function() {
var thisDiv = $(this), // cache this element
thisData = thisDiv.data(), // get all data attributes
thisCSS = {}; // create the css array
// Check which data is set and update the css accordingly
if (thisData['mt']) {
thisCSS['margin-top'] = thisData['mt'] + 'px';
}
if (thisData['mb']) {
thisCSS['margin-bottom'] = thisData['mb'] + 'px';
}
if (thisData['pt']) {
thisCSS['padding-top'] = thisData['pt'] + 'px';
}
if (thisData['pb']) {
thisCSS['padding-bottom'] = thisData['pb'] + 'px';
}
// Add the css to this element
thisDiv.css(thisCSS);
// The following two lines show the data in each div for debugging.
// Remove these lines when you don't need this info anymore.
thisDiv.append('<div>CSS: ' + JSON.stringify(thisCSS) + '</div>');
thisDiv.append('<div>DATA: ' + JSON.stringify(thisData) + '</div>');
});
});
</script>
Here is the JSFiddle.
And here is the jQuery Documentation on .data().
Also check out the data-attribute documentation here.

ajax request returns status = 0 for submit event but works with status=200 for keyup event

I am having a problem with the following javascript/ajax code. The code searches a JSON file which just has some contact names and email addresses in it. When the "keyup" event calls addr.search everything is fine and in the function call to ajaxCall the attributes request.readyState=4 and request.Status=200, but when the "submit" event calls the same search calling the same addr.search function the request.status is 0 and it fails.
Is it possible it has something to do with the action attribute in the form element?
I should add that I am running this on a WAMP server.
/* standard Ajax xhr function */
function getHTTPObject() {
var xhr;
if (window.XMLHttpRequest) { // check for support
// if it's supported, use it
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // check for the IE 6 Ajax
// save it to the xhr variable
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
// spit out the correct one so we can use it
return xhr;
}
/* define the Ajax call */
function ajaxCall(dataUrl, outputElement, callback) {
/* use our function to get the correct Ajax object based on support */
var request = getHTTPObject();
outputElement.innerHTML = "Loading";
request.onreadystatechange = function() {
// check to see if the Ajax call went through
if ( request.readyState === 4 && request.status === 200 ) {
// save the ajax response to a variable
var contacts = JSON.parse(request.responseText);
// make sure the callback is indeed a function before executing it
if(typeof callback === "function"){
callback(contacts);
} // end check
} // end ajax status check
} // end onreadystatechange
request.open("GET", dataUrl, true);
request.send(null);
}
/* wrap everything in an anonymous function to contain the variables */
(function(){
/* define the DOM elements and common variables you'll need */
var searchForm = document.getElementById("search-form"),
searchField = document.getElementById("q"),
getAllButton = document.getElementById("get-all"),
target = document.getElementById("output");
/* define address book methods */
var addr = {
search : function(event){
// set the output element
var output = document.getElementById("output");
ajaxCall('data/contacts.json', output, function (data) {
// save the input value, contacts length and i to variables
var searchValue = searchField.value,
addrBook = data.addressBook,
count = addrBook.length,
i;
// stop the default behavior
event.preventDefault();
// clear the target area just incase there's something in it.
target.innerHTML = "";
// check the count, of course
if(count > 0 && searchValue !== ""){
// loop through the contacts
for(i = 0; i < count; i = i + 1) {
// look through the name value to see if it contains the searchterm string
var obj = addrBook[i],
isItFound = obj.name.indexOf(searchValue);
// anything other than -1 means we found a match
if(isItFound !== -1) {
target.innerHTML += '<p>' + obj.name + ', '+ obj.email +'<p>';
} // end if
} // end for loop
} // end count check
}); // end ajax call
},
getAllContacts : function () {
// set the output element
var output = document.getElementById("output");
// start Ajax call
ajaxCall('data/contacts.json', output, function (data) {
var addrBook = data.addressBook,
count = addrBook.length,
i;
// clear the target area just incase there's something in it.
target.innerHTML = "";
// check the count, of course
if(count > 0) {
// loop through the contacts
for(i = 0; i < count; i = i + 1) {
// look through the name value to see if it contains the searchterm string
var obj = addrBook[i];
target.innerHTML += '<p>' + obj.name + ', '+ obj.email +'<p>';
} // end for loop
} // end count check
}); // end ajax call
},
setActiveSection : function() {
// add a class of "active" the wrapping div
this.parentNode.setAttribute("class", "active");
},
removeActiveSection : function() {
// remove the class from the wrapping div
this.parentNode.removeAttribute("class");
},
addHoverClass : function() {
// remove the class from the wrapping div
searchForm.setAttribute("class", "hovering");
},
removeHoverClass : function(){
// remove the class from the wrapping div
searchForm.removeAttribute("class");
}
} // end addr object
// activate auto complete on keyUp
searchField.addEventListener("keyup", addr.search, false);
// set active section on focus of the form field
searchField.addEventListener("focus", addr.setActiveSection, false);
// remove active section on blur of the form field
searchField.addEventListener("blur", addr.removeActiveSection, false);
// get all contacts when you click the button
getAllButton.addEventListener("click", addr.getAllContacts, false);
// add hover class on mouse over of the form field
searchForm.addEventListener("mouseover", addr.addHoverClass, false);
// remove hover class on mouse out of the form field
searchForm.addEventListener("mouseout", addr.removeHoverClass, false);
// activate search on form submit
searchForm.addEventListener("submit", addr.search, false);
})(); // end anonymous function
Here is the html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Address Book Application</title>
<style>
.active { background:#ddd; }
.hovering { background:#eee; }
form > div { padding:10px; }
</style>
</head>
<body>
<h1>Address Book</h1>
<form action="" method="get" id="search-form">
<div>
<label for="q">Search address book</label>
<input type="search" id="q" name="q" required placeholder="type a name" autocomplete="off">
</div>
<div class="button-group">
<button type="submit" id="search-btn">search</button>
<button type="button" id="get-all">get all contacts</button>
</div><!--/.button-group-->
</form>
<div id="output" aria-atomic="true" aria-live="polite"></div><!--/#output-->
<script src="js/addressbook.js"></script>
</body>
</html>
and the JSON file:
{
"addressBook" : [
{
"name": "hillisha",
"email": "hill#example.com"
},
{
"name": "paul",
"email": "cleveland#example.com"
},
{
"name": "vishaal",
"email": "vish#example.com"
},
{
"name": "mike",
"email": "grady#example.com"
},
{
"name": "jamie",
"email": "dusted#example.com"
},
{
"name": "gini",
"email": "g#example.com"
},
{
"name": "kristen",
"email": "marv#example.com"
},
{
"name": "starlen",
"email": "stars#example.com"
},
{
"name": "archie",
"email": "ie#example.com"
},
{
"name": "bill",
"email": "hickey#example.com"
}
]
}
You're not stopping the default action. It doesn't matter for the keyup event, but the form does get submitted (with an action="" to the same location so you're not really noticing it). On leaving the page, the runnning ajax requests get aborted and you see the status code 0.
The problem is that you're invoking event.preventDefault(); from the ajax callback - it's too late then, all event-related actions have already been run. Move it to the first line of your addr.search function.

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories