loop do only last value but it do all in debug mod - javascript

My loop is supposed to downolad all the href of the page with the tagName a but it only download the last file of the loop.
$('#exportBilanProj').click(
function() {
var links = document.getElementsByTagName('a');
for(var count=0; count<links.length; count++) {
var url = links[count].getAttribute('href');
if(url && url.startsWith('rest/grm/export/bilan-projet/')) {
console.log( "value :" + url );
links[count].dispatchEvent(new MouseEvent('click'));
}
}
});
but when I debug it all the information are taken and all file are downloaded
value :rest/grm/export/bilan-projet/53035
value :rest/grm/export/bilan-projet/53039
value :rest/grm/export/bilan-projet/64001
I tried a break but nothing worked. Any idea ?

why do not you use the "window.open"? I used this example and it looks like it worked correctly!
var links = document.getElementsByTagName('a');
for(var count=0; count<links.length; count++) {
var url = links[count].getAttribute('href');
//remove for tests
//if(url && url.startsWith('rest/groupama/export/bilan-projet/')) {
console.log( "value :" + url );
//window.open
window.open(url);
//}
}
if the link you open is that of a download, it will just start downloading, if you use a compound url, you will have to adjust this before the "window.open (url)" example:
window.open(location.href + url);
or something like this...

Related

Intercept incoming URL with javascript

When a user navigates to my site with a qualified URL (e.g. mysite.com/abc.html) I want to call a javascript function first before showing any pages. I need that because my site is driven by ajax.
I have a function that’s called when the page is first loaded:
<body onload="FirstJSFunction(150);”>
That function will intercept the URL and do what I want, but only if the qualified URL is mysite.com/index.html. Any other valid URL within the site will bypass the javascript function and load the requested page. That’s not what I want.
Here is how FirstJSFunction handles it:
<script>
function FirstJSFunction(type) {
var gurl = GetURL();
length = gurl.length;
console.log("SFR URL " + length);
var pos = gurl.lastIndexOf("/");
console.log ("SFR_LastFwdSlash " + pos);
if (length > pos) {
var sub1 = gurl.substr(pos, length);
console.log ("SFR_Sub1 " + sub1);
sub2 = sub1.substr(1, 5);
console.log ("SFR_Sub2 " + sub2);
if (sub2 == "index") {
ShowAjax(3);
return true; }
if (sub2 != "index") {
ShowAjax(3);
return true; }
}
</script>
<script>
function GetURL() {
var loc_href = location.href;
console.log ("URL " + loc_href);
var length = loc_href.length;
console.log ("Length " + length);
var pos = loc_href.lastIndexOf("/");
console.log ("LastFwdSlash " + pos);
var pos2 = loc_href.indexOf("/");
console.log ("FwdSlash " + pos2);
if (length > pos) {
var substr = loc_href.substr(pos, length);
console.log ("Substring " + substr);
return substr; }
}
</script>
So my question is: when the user navigates to my site with any URL other than mysite.com or mysite.com/index.html – for example mysite.com/abc.html – why doesn’t the code above work to intercept the URL and call the javascript function, as happens if the URL is index.html.
Just to clarify, I only want to intercept the first incoming URL. I am not looking to intercept any URL the user enters into the address bar after they have arrived at my site.
Thanks for any help on this.
I'm not sure about everything you explained, so making some assumptions here.
But if that JS code is only on index.html, then it will never run for any other page. For that you would need to include it in every page.
Only the server is able to "see" all the pages accessed by your users.

How to display images one at a time through loop with HTML/Javascript?

I'm not one of those people that grew up with programming, or have experienced in high school. I just recently started the basics in College. What I have below is my javascript/html that I have been working on Visual Studio 2012. My goal for it is to display the images one at a time by pressing a button called "Next Name" (as you can see I created a "form" at the bottom of my code). But as I have it now, it prints out all the images in my "hw1.txt" at the same time. Under my for loop, I tried "result = "";" and then "displayList.innerHTML = result;" hoping to just print out one image at least. I tried other things, but it just left my code messy. Please I need help. Any advice, pointers, or whatever is good. Can you also explain your answers in a way that I'll understand too? Just think of me as you're talking to a child or something haha. Thanks.
Note: in "hw1.txt" every 3rd index (starting from index 0) is the name of people, and the index next to it (myArray[i + 1]) is the image file (inside the .txt it goes like 1.jpg, 2.jpg, 3.jpg, and so on...)
<br/>
<span id="displayList">Photo here.</span>
<script type=text/javascript>
if (typeof ActiveXObject != "undefined") // IE
var req = new ActiveXObject("Microsoft.XMLHTTP");
else // Other browsers
var req = new XMLHttpRequest();
req.open('GET', 'hw1.txt', false);
req.send(null);
s = req.responseText;
var myArray = s.split(";");
var result = "";
function nextItem() {
for (i = 3; i < myArray.length; i = i + 3)
result = result + "<img src='" + myArray[i + 1] + "'/>";
displayList.innerHTML = result;
}
</script>
<form name="ClickNext">
<input type="button" value="Next Name" onclick="nextItem()" />
</form>
<span id="displayList">Photo here.</span>
<script type=text/javascript>
if (typeof ActiveXObject != "undefined") // IE
var req = new ActiveXObject("Microsoft.XMLHTTP");
else // Other browsers
var req = new XMLHttpRequest();
req.open('GET', 'hw1.txt', false);
req.send(null);
s = req.responseText;
var myArray = s.split(","); //if images are comma(,) seperated then just split it from comma
var index = 0;
function nextItem() {
if(typeof myArray[index] !== 'undefined') {
displayList.innerHTML = "<img src='" + myArray[index] + "'/>";
index += 1;
}
}
</script>
<form name="ClickNext">
<input type="button" value="Next Name" onclick="nextItem()" />
</form>
First off you don't need the form around that input since you don't really send a form.
Secound you should add an id to your input ( or <a></a> or <button></button> ) such as id="next_name" or I guess you can keep the old way of calling an event. :P
Then, you should:
var position = 0;
var result = '';
document.getElementById('next_name').onclick = function(){
if(position < myArray.length){
result = result + "<img src='" + myArray[position + 1] + "'/>";
displayList.innerHTML = result;
position++;
}
};
The idea is to use a variable to memorize your position within your list of image srouces. Once you use one, you increment your position within the list so next time a user clicks that button you add a different image.

remove first half of string but keep second half in javascript or jquery

I recently created my own personal portal page to replace iGoogle since it's going to be shuttered later this year. Everything is working fine except that one of the RSS feeds that I'm pulling in outputs urls that look like this: http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305
Which when clicked go to a bad url page. How would I remove the first half of that url so that it only has the part starting from the second http://
Strange, but here the link works fine...
Just realized the issue is that somehow the ampersands are being turned into entities which is breaking the links...
Try this. A generic approach.
function queryString(parameter, url) {
var a = document.createElement("a");
a.href = url;
var loc = decodeURIComponent(a.search.substring(1, a.search.length));
var param_value = false;
var params = loc.split("&");
for (var i = 0; i < params.length; i++) {
param_name = params[i].substring(0, params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=') + 1)
}
}
if (param_value) {
return encodeURIComponent(param_value);
}
else {
return "";
//param not found
}
}
var secondHTTP = queryString("url", 'http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305');
var str = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305";
var url = decodeURIComponent(str.split(/https?:/ig).pop());
will result in
"//www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
or
var url = decodeURIComponent(str.match(/^http.+(http.+)/i)[1]);
will result in
"http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
Edit: Code updated, jsFiddle added
HTML:
<input id="schnitzel" type="text" value="http://www.google.com/http://www.real-foo.bar/" />
<input type="button" onclick="$('#schnitzel').val(window.firstHTTP($('#schnitzel').val()));" value="»" />
JavaScript:
window.firstHTTP = function (furl = "") {
var chunked = furl.split("http://");
return (chunked && chunked[2]) ? ("http://" + chunked[2]) : furl;
};
JS-Fiddle:
http://jsfiddle.net/Rm5bU/

Get the element below the ready-function code, in jQuery?

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 + '".');
}
} );

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