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)
Related
My goal is to load data from the appropriate file into div sections when I select any option.
I need to load <div> in one file from another (inside iframe). I'm stuck on how to get value and store it in variable. Everything works fine if I assign to variables (template_1, template_2, template_3) any static data but I want to load it from another files (template_one.html, template_2.html and so on).
template_1 has load() method but I know that this is wrong. Instead I want a path to appropriate file div. Same with other variables
I found a similar solution here with function load but I'm not sure if this will work and how add this to my function.
Array objects are random so please don't worry about it
jQuery(document).ready(function($) {
var template_1 = $('#section_one').load('template_one.html', '.section_one')
var template_2 = "<div><h1>template2</h1></div>"
var template_3 = "<div><h1>template3</h1></div>"
var templates_array = [
[template_1, template_1, template_1, template_1, template_1],
[template_2, template_2, template_2, template_2, template_2],
[template_3, template_3, template_3, template_3, template_3],
]
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
document.getElementById('id_template').onchange = function(event) {
let get_val = event.target.selectedOptions[0].getAttribute("value");
if (get_val) {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = templates_array[get_val - 1][i];
};
} else {
for (let i = 0; i < templates_array.length; i++) {
var iframe = document.getElementsByTagName('iframe')[i].contentWindow.document;
var iframe_content = iframe.querySelector('body');
iframe_content.innerHTML = '';
};
};
};
});
project tree
Jquery Code
$(document).ready(function(){
$(document).on('click', '#button_1', function() {
$('#div_1').load('one.html')
});
$(document).on('click', '#button_2', function() {
$('#div_2').load('two.html')
})
});
HTML Code
Button_1
<BR>
<BR>
Button_2
<BR>
<BR>
<div id="div_1"></div>
<div id="div_2"></div>
I hope this one help you.
In the iframe:
<textarea id="ta"></textarea>
<script>
$(document).ready(function(){
$(document).on('change', '#ta', function() {
parent.textAreaChanged(this.value);
});
});
</script>
In the parent:
<div id="display"></div>
<script>
function textAreaChanged(value){
$('#display').text(value);
}
</script>
I'm back and i tried it but is doesn't work anyone that can help??? i have already put in the save mechanism.
(i had to add extra text so this has nothing to do with the script itself)
this is the code that i used to test the save mechanism.
<!DOCTYPE html>
<html>
<body>
<button onclick="point();">points</button>
<button onclick="upgrade()">upgrade</button>
<script language="javascript">
var pointcount = 0;
var totalcliks = 0;
var upgrades = 0;
function point() {
pointcount++;
totalcliks++;
}
function upgrade() {
upgrades++;
pointcount--;
}
function load() {
var testerload = document.getElementById("savecodetextbox").value;
document.getElementById("saveshow").innerHTML = testerload;
}
var pointcounterclock = setInterval(function() {pointcounter()},100);
function pointcounter(){
document.getElementById("points-screen").innerHTML = pointcount+" points";
document.getElementById("clicktotal").innerHTML = totalcliks+" totalcliks";
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
}
let savecode = "1a1a1"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[1];
updates = codes[2];
pointcount = codes[3];
}
</script>
<h3 id="points-screen"></h3>
<h3 id="clicktotal"></h3>
<h3 id="savecode"></h3>
<textarea name="text_area" id="savecodetextbox" rows="4" cols="40"></textarea> <button onclick="load()">load</button>
<h3 id="saveshow"></h3>
</body>
</html>
I'm going to alter your save code so I don't have to confuse you with regular expressions or funky splits:
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
Which means your save code could look something like: 4a6a9
Do a simple split:
let savecode = "4a5a6"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[0];
upgrades = codes[1];
pointcount = codes[2];
}
As for implementing the variables, reload the game after
i have an auto-suggest url from that i need to write a JavaScript code through which i will be able to see the auto-suggest data.
i tried the below code but i am not able to get through it.
<!DOCTYPE html>
<head>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://***.poc.xxxxx.com/v1/staples/suggest?authKey=baef7f8e39c512342c8a14b7f6018b58&q=wat&rows=8";
var words = []
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var data = JSON.parse(response);
var req_data = data.suggestions[0].suggestion;
console.log(req_data);
//document.getElementById("id01").innerHTML = words;
}
</script>
</head>
<body>
<!-- <div id="id01"></div> -->
</body>
</html>
the thing i am getting in response is:-
{"suggestions":[{"suggestion":"\u200B\u200B\u200B<b>wat</b>er","categories":[{"name":"Water & Juice","filter":"category_id%3A4606"},{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er cooler","categories":[{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"},{"name":"Kitchen Storage & Organization","filter":"category_id%3A1303"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er bottle","categories":[{"name":"Lunch Totes & Water Bottles","filter":"category_id%3A8812"},{"name":"Water & Juice","filter":"category_id%3A4606"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er cups","categories":[{"name":"Disposable Plates & Cups","filter":"category_id%3A992"},{"name":"Disposable Cups","filter":"category_id%3A13302"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er bottle labels","categories":[{"name":"Labels","filter":"category_id%3A997"},{"name":"Mailing & Shipping Labels","filter":"category_id%3A6118"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er dispenser","categories":[{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"},{"name":"All Kitchen","filter":"category_id%3A60479"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>ch","categories":[{"name":"Pedometers & Fitness Trackers","filter":"category_id%3A2554"},{"name":"Smart Watches","filter":"category_id%3A62030"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>ercolor","categories":[{"name":"Abstract Art","filter":"category_id%3A12645"},{"name":"Wall Art/Decor","filter":"category_id%3A26678"}]}]}
from that response i need to find all the product name which coming after suggestion not suggstions like suggestion for wat water cooler etc.
It is hard to discern what exactly you're asking for. If what you want is just a list of all the "name" properties that are returned as suggestions, you could collect those like this:
function myFunction(response) {
var data = JSON.parse(response);
var items = data.suggestions;
var names = [], cat;
// iterate array of suggestions
for (var i = 0; i < items.length; i++) {
cat = items[i].categories;
// iterate array of categories in each suggestion
for (var j = 0; j < cat.length; j++) {
names.push(cat[j].name);
}
}
console.log(names.join(","));
}
Working demo: http://jsfiddle.net/jfriend00/trdppth0/
Now that you've clarified what output you want, you can get the list of suggestion words like this:
function myFunction(response) {
var data = JSON.parse(response);
var items = data.suggestions;
var suggestions = items.map(function(item) {
return item.suggestion;
});
console.log(suggestions.join(","));
}
Working demo: http://jsfiddle.net/jfriend00/bv3yfkwr/
I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.
For example:
<script>
$(document).ready( function() {
alert( $(this).getBelowElementToThisScript('form').id );
});
</script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
This code should show this message: IamTheNext
In addition, the solution needs to work with this example too:
<script src="getbelowelement.js"></script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
Thanks
Try this:
var form = $('script[src="getbelowelement.js"]').next();
But I would suggest using the forms id:
var form = $('#IamTheNext');
You could also try giving the script tag an id.
This kind of approach is dangerous; script should never depend that much on where it is in the page.
That said, the following works in Firefox and Chrome and should work in the major browsers (use at your own risk).
See it in action at jsBin. Both <script> ... and <script src="..."> approaches are shown in the same page.
$(document).ready( function () {
invocationsOfThis = (typeof invocationsOfThis == 'number') ? invocationsOfThis + 1 : 1;
var scriptTags = document.getElementsByTagName ('script');
var thisScriptTag = null;
//--- Search scripts for scripts of this type.
for (var foundCnt = 0, J = 0, L = scriptTags.length; J < L; ++J)
{
/*--- Since the script can be either inline or included, search
both the script text and the script src link for our unique
identifier.
*/
var thisTag = scriptTags[J];
var scriptCode = thisTag.innerText || thisTag.textContent;
var scriptSrc = thisTag.src;
//--- IMPORTANT, change pastebin.com to the filename that you use.
if (/invocationsOfThis/i.test (scriptCode) || /pastebin.com/i.test (scriptSrc))
{
//--- Found a copy of this script; is it the right one, based on invocation cnt?
foundCnt++;
if (foundCnt == invocationsOfThis) {
thisScriptTag = thisTag;
break;
}
}
}
if (thisScriptTag) {
//--- Get the target node.
var nextForm = $(thisScriptTag).next ('form');
var nextFormId = nextForm.attr ('id');
//--- Act on the target node. Here we notify the user
nextForm.text ('This is form: "' + nextFormId + '".');
}
} );