JavaScript Find Specific URLs. - javascript

Alright, I've been working on a userscript that redirects when a specific page is loaded.
This is what I have so far:
function blockThreadAccess() {
var TopicLink = "http://www.ex.com/Forum/Post.aspx?ID=";
var Topics = [ '57704768', '53496466', '65184688', '41182608', '54037954', '53952944', '8752587', '47171796', '59564382', '59564546', '2247451', '9772680', '5118578', '529641', '63028895', '22916333', '521121', '54646501', '36320226', '54337031' ];
for(var i = 0; i < Topics.length; i++) {
if(window.location.href == TopicLink + Topics[i]) {
// Execute Code
}
}
}
The function is called on the page load, but it doesn't seem execute the code.
What it's supposed to do is check to see if the user is on that specific page, and if he is then execute the code.
Say someone goes to this link - http://www.ex.com/Forum/Post.aspx?ID=54646501, it then redirects the use. I'm trying to make it efficient so I don't have to add a bunch of if statements.

try converting both to lower case before comparing
var loc = window.location.href.toLowerCase();
var topicLnk = TopicLink.toLowerCase();
for(var i = 0; i < Topics.length; i++) {
if(topicLnk + Topics[i] == loc) {
// Execute Code
}
}

Related

Is it possible to change a string parameter with a For Loop?

I'm not a programmer, neither studying something related to it, but just someone who wants to run a code to make my work life easier.
I need to open 50 tabs. Opening one by one takes so much time because when I click the open button, it shows me the new tab opened and then I have to go back to the original page to open the next one and so on.
After a weekend of doing some research, I found that Google Chrome has a "Console" that can be modified to make a webpage work as you want.
The code that runs to open a tab in this webpage is the following. I've run this code in the console and surprisingly it works:
if(typeof jsfcljs == 'function'){
jsfcljs(document.getElementById('ngFindListForm'), {'ngFindListForm:tblDataTable:0:j_id178':'ngFindListForm:tblDataTable:1:j_id178'},'_blank');}
And to open the next tab is:
if(typeof jsfcljs == 'function'){
jsfcljs(document.getElementById('ngFindListForm'),{'ngFindListForm:tblDataTable:1:j_id178':'ngFindListForm:tblDataTable:1:j_id178'},'_blank');}
As you see, the "only" part of code that changes is the number between colons (0 and 1).
So, according to my basic-high school-programming skills, I think I can change those number with a For Loop from 0 to 49 (50 tabs). I've tried that like this:
for (i = 0; i < 50; i++) {
param = 'ngFindListForm:tblDataTable:' + i +':j_id178';}
And then using this param something like this:
if(typeof jsfcljs == 'function'){
jsfcljs(document.getElementById('ngFindListForm'),{param:'ngFindListForm:tblDataTable:1:j_id178'},'_blank');}
But it's not working. It just makes to open the same page I'm on in a new tab.
Maybe the logic I have figured out how to make this work is totally wrong, but this is why I came here to ask you.
Thanks
move your code inside foreach and use [param] (ES6)
var form = document.getElementById('ngFindListForm');
if (typeof jsfcljs == 'function') {
for (i = 0; i < 50; i++) {
var param = 'ngFindListForm:tblDataTable:' + i + ':j_id178';
jsfcljs(form, {
[param]: 'ngFindListForm:tblDataTable:1:j_id178'
}, '_blank');
}
}
OR
var form = document.getElementById('ngFindListForm');
if (typeof jsfcljs == 'function') {
for (i = 0; i < 50; i++) {
var obj = {};
obj['ngFindListForm:tblDataTable:' + i + ':j_id178'] = 'ngFindListForm:tblDataTable:1:j_id178';
jsfcljs(form, obj, '_blank');
}
}
There are a few ways to do it, the easiest would be to use an object and set the string
function jsfcljs(e, o, t) {
console.log(o);
}
for (let i = 0; i < 5; i++) {
var obj = {}
obj['ngFindListForm:tblDataTable:' + i + ':j_id178'] = 'ngFindListForm:tblDataTable:' + i + ':j_id178'
jsfcljs(document.getElementById('ngFindListForm'), obj, '_blank');
}
<div id="ngFindListForm"></div>

Javascript HTML include results in duplicate includes in random places

This problem has me absolutely stumped. I'm trying to include HTML snippets with Javascript and it works, but for some reason it decides to also include duplicate snippets in various other locations.
Here is a screenshot of what I mean:
It also varies the number and location of these random includes.
This is the function I use to include. It searches through the document and finds div elements with the attribute include="x.html"
function include() {
var allElements;
var fileName;
var includeRequest;
allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute("include")) {
fileName = allElements[i].getAttribute("include");
includeRequest = new XMLHttpRequest();
includeRequest.open("GET", fileName, true);
includeRequest.onreadystatechange = function() {
if (includeRequest.readyState == 4 && includeRequest.status == 200) {
allElements[i].removeAttribute("include");
allElements[i].innerHTML = includeRequest.responseText;
include();
delete includeRequest;
includeRequest = null;
}
}
includeRequest.send();
return;
}
}
}
This is the function that gets tags from an html file containing articles, and adds them to the list of tags in the box on the right. As you can see, in one place the footer is added to the list instead of the tag. I don't know why.
function getTags() {
var taglist = document.getElementById("taglist");
var tagsRequest = new XMLHttpRequest();
tagsRequest.open("GET", "blogstubs.html", true);
tagsRequest.responseType = "document";
tagsRequest.onreadystatechange = function() {
if (tagsRequest.readyState == 4 && tagsRequest.status == 200) {
var tagsResponse = tagsRequest.responseXML;
var tags = tagsResponse.getElementsByClassName("tag");
var tags = getUnique(tags);
var len = tags.length;
for (var i = 0; i < len; i++) {
var li = document.createElement("li");
li.appendChild(tags[i]);
taglist.appendChild(li);
}
delete tagsRequest;
tagsRequest = null;
}
}
tagsRequest.send();
}
Javascript only solution please. Ideas?
I copied your website (I hope you don't mind) and tested it with my changes, it seems to be working now without this bug. Here's what I did:
1) I created a new function, don't forget to change the name to whatever you prefer:
function newFunction(allElements, includeRequest) {
allElements.removeAttribute("include");
allElements.innerHTML = includeRequest.responseText;
include();
delete includeRequest;
includeRequest = null;
}
2) I changed the include() function to look like this:
function include() {
var allElements;
var fileName;
var includeRequest;
allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].getAttribute("include")) {
var element = allElements[i];
fileName = element.getAttribute("include");
includeRequest = new XMLHttpRequest();
includeRequest.open("GET", fileName, true);
includeRequest.onreadystatechange = function() {
if (includeRequest.readyState == 4 && includeRequest.status == 200) {
return newFunction(element, includeRequest);
}
}
includeRequest.send();
return;
}
}
}
I think the problem was caused by async nature of AJAX requests, like I said in the comment. So you need to pass the variables to your AJAX call instead of using the global scope, that's why you need this new callback function.
In other words, in the original code the AJAX variable allElements[i] wasn't in sync with your loop's allElements[i], so while in your loop it would be 5, in AJAX function (which executed separately and not in order with the loop) it would be 3, 6 or whatever else. That is why it would append the html to the element that seems random. Think of AJAX as of someone who doesn't care about the order of your loops, someone who really doesn't like to wait while someone else is counting and does everything in his own order.

Extending a google spreadsheet into a google web app

I was coding using the google scripts, when I came across a problem I've been struggling with for a couple days now. I am using Code.gs (a default page in creating a web app in google), when I called in data from a google spreadsheet to try and display it on a webpage. I had no problems with calling in the data add storing it into a array but now I am struggling with trying to return it to my javascript code. Can this be done or is there something else I can do to fix it? My code is below.
function getContents()
{
var sheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1xum5t4a83CjoU4EfGd50f4ef885F00d0erAvUYX0JAU/edit#gid=0&vpid=A1');
var range = sheet.getDataRange();
var values = range.getValues();
for (var i = 0; i < values.length; i++) {
var education = [];
for (var j = 0; j < values[i].length; j++) {
if (values[i][j]) {
if(j==1){
education[education.length] = values[i][j];
}
}
}
}
Logger.log(education);
return education;
}
From that Code.gs code i want it to return it to a Javascript function that says this:
function onNew(){
var input = google.script.run.getContents();
for(var = 0; i<input.length; i++)
{
$("#main").append("<div id='class'>"+input[i]+"</div>);
}
}
and whenever I try to run it says that it causes an error because it is undefined. Thanks in advance! Anything helps!
You need to use the withSuccessHandler(). Your variable input will not receive the return from google.script.run.getContents()
Separate out the client side code into two functions:
HTML Script
function onNew() {
google.script.run
.withSuccessHandler(appendEducationHTML)
.getContents();
};
function appendEducationHTML(returnedInfo) {
console.log('returnedInfo type is: ' + typeof returnedInfo);
console.log('returnedInfo: ' + returnedInfo);
//If return is a string. Convert it back into an array
//returnedInfo = returnedInfo.split(",");
for (var = 0;i < returnedInfo.length; i++) {
$("#main").append("<div id='class'>"+returnedInfo[i]+"</div>);
};
};

Local variables giving global trouble

I'm a JS super n00b.
I asked about an aspect of this problem in this post (Puzzling behavior from IF ( ) statement) on IF statements but it looks like the actual issue is related to the scope of a variable I've created. It seems that after declaring (what I think is) a global variable, other functions in the code cannot access the variable.
I'm doing JS project/program that prompts a user to input a word and the program reverses the word input.
In the previous post (PP) a user correctly determined that I was getting the 'false' console message (see code) no matter what the length of the word input because I was assigning value the variable when the page loads but not reading it again when the user clicks the button on the page.
If the variable 'word' is local I'm only able to get a 'false' console message and when the variable 'word' is global I'm only able to get a 'ReferenceError.'
Any ideas anyone has are greatly appreciated.
See JS code below:
var word = document.getElementById('wordChoice').value;
var lttrs = [];
function flipFail () {
alert("Please enter a word of at least two characters.");
console.log(false);
var inputErrArr = ['has-error', 'has-feedback'];
var inputErrFdbk = ['glyphicon', 'glyphicon-remove'];
wordChoice.style.backgroundColor = "#FFDBAA";
for (var i = 0; i < inputErrArr.length; i ++) {
addClass(wordInput, inputErrArr[i]);
}
for (var i = 0; i < inputErrFdbk.length; i ++) {
addClass(glyph, inputErrFdbk[i]);
}
document.getElementById('wordChoice').value = " ";
} // END flipFail()
function flipSuccess (){
for (var i = 0; i < word.length; i ++) {
lttrs.push(word.charAt(i));
}
lttrs.reverse();
var reversedWord = lttrs.join('')
alert("Your reversed word is: " + reversedWord);
console.log(true);
document.getElementById("flip").innerHTML = "Flip Again!";
document.getElementById('wordChoice').value = " ";
} // EN flipSuccess ()
function flipChk () {
if (word.length < 2) {
flipFail ();
} else {
flipSuccess ();
}
}
See fully implemented code here: http://supsean.com/supsean/flipr/flipr.html
You need to set word in flipChk(). You're setting it when the page is first loaded, before the user has entered anything into the form, not when the user clicks on the Flip button.
Then, instead of using a global variable, pass it as an argument to the function. In general, avoid using global variables unless you really have to.
function flipChk () {
var word = document.getElementById('wordChoice').value;
if (word.length < 2) {
flipFail ();
} else {
flipSuccess (word);
}
}
function flipSuccess (word){
var lttrs = [];
for (var i = 0; i < word.length; i ++) {
lttrs.push(word.charAt(i));
}
lttrs.reverse();
var reversedWord = lttrs.join('')
alert("Your reversed word is: " + reversedWord);
console.log(true);
document.getElementById("flip").innerHTML = "Flip Again!";
document.getElementById('wordChoice').value = " ";
} // EN flipSuccess ()

HTML rendering before for-loop finishes executing, only first item in for-loop showing

I am trying to render an html page that contains all of the posts that a user has received. Right now the issue I am having (shown under Way 1) is that when I call the function renderPosts after the web socket is received, only the first post in the array is rendered (the array has more than one post in it).
On the other hand, Way 2 in which I have no for loop and instead manually render each post works in that all four posts are rendered. But I need to be able to work with an arbitrary number of posts which is why I need to use the for loop.
I am using socket.io and javascript.
Way 1:
socket.on('postsToRender', function(arrayOfPostsToRender) {
renderPosts(arrayOfPostsToRender);
});
function renderPosts(arrayOfPostsToRender) {
for (var index = 0; index < arrayOfPostsToRender.length; index++) {
renderPost(arrayOfPostsToRender[index]);
}
}
function renderPost(postToRender) {
var feed = document.getElementById("feed");
var postContent = document.createTextNode(postToRender.content);
var post = document.createElement("div");
post.appendChild(postContent);
feed.appendChild(post);
}
Way 2:
socket.on('postsToRender', function(arrayOfPostsToRender) {
renderPost(arrayOfPostsToRender[0]);
renderPost(arrayOfPostsToRender[1]);
renderPost(arrayOfPostsToRender[2]);
renderPost(arrayOfPostsToRender[3]);
});
function renderPost(postToRender) {
var feed = document.getElementById("feed");
var postContent = document.createTextNode(postToRender.content);
var post = document.createElement("div");
post.appendChild(postContent);
feed.appendChild(post);
}
Try this:
function renderPosts(arrayOfPostsToRender) {
for (var index = 0; index < arrayOfPostsToRender.length; index++) {
(function(i){
renderPost(arrayOfPostsToRender[i]);
})(index);
}
}

Categories

Resources