Executing Javascript code after loading refreshed page - javascript

I have a Javascript file that is split into to two parts. The first part of the code ends by refreshing the current page. I would like to try to get the second part of the code to execute as soon as the page reloads, but I am having trouble finding a way to implement this. I pretty much want a way to do
window.onload = someFunction()
except that it activates the function after reloading the page due to the first part of the Javascript. Is there an effective way to do this?

You could do that using Jquery.
This is executed on page loading
$(function() {
callMyFunction()
});

Use
document.onload = somefunction()
Instead . This will get executed immediately after the DOM loads .
You can also use the jQuery to do the same like
$(document).ready(function(){
somefunction();
});

The only way I can think of is to add query string value when refreshing, then read that value and act upon it.
You can use such code:
function ParseQueryString() {
var result = [];
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var reloaded = QS["reloaded"];
if (reloaded === "1") {
//execute second part of code
}
}
Then when reloading, redirect to same page adding ?reloaded=1 otherwise (if this flag is already raised) don't refresh the page again to avoid infinite loop.

Related

Problem with infinite loop when manipulating DOM

I'm learning about DOM manipulation and, to practice, I'm trying to get the first 100 Twitter users who have twitted about #Javascript (see link). As, for now, Twitter doesn't allow you to use console.log() function in the browser console, I have managed to show any string visually in the HTML, in this case, under the search textbox.
This is my "custom" console.log()
function consoleLog(data) {
var searchTextBox = document.querySelector("#doc > div.topbar.js-topbar > div > div > div > div > div");
var p = document.createElement("p");
var innerText = document.createTextNode(data);
p.appendChild(innerText);
searchTextBox.appendChild(p);
}
For getting the usernames, I keep scrolling the page every 4 seconds and looking for usernames until I have 100 or more of them in my usernames variable.
var scrollPage = setInterval(function() {
window.scrollTo(0, document.body.scrollHeight);
}, 4000);
var usernames = [];
while (true) { // <------ PROBLEM
if (usernames.length < 100) {
consoleLog("Getting usernames again");
usernames = getUsernames();
}
else {
consoleLog("We have ENOUGH usernames. BREAK");
clearInterval(scrollPage);
printUsernames();
break;
}
}
function printUsernames() {
for(var user of usernames) {
consoleLog(user);
}
}
function getUsernames() {
var results = [];
var usernameNodes = document.getElementsByClassName("username u-dir u-textTruncate");
var username = usernameNodes[0].textContent;
for(var node of usernameNodes) {
results.push(node.textContent);
}
return results.filter(isUnique);
}
function isUnique(value, index, self) {
return self.indexOf(value) === index;
}
The problem is that the while loop enters in infinte loop and I don't know why. I think the logic of the code is correct. In fact, if I first copy and paste all the declared functions to the browser console, then start the scrollPage interval and, lastly, start the while loop, it works well. The problem comes when I copy and paste all the code at one time in the browser console. It is like the executions of the interval and the while loop conflict in some way. But I can't understand.
Its better to have while conditioned like this:
var usernames = [];
// This will automatically end when length is greater or equall 100
// no need to break
while (usernames.length < 100) {
consoleLog("Getting usernames again");
usernames = getUsernames();
}
consoleLog("We have ENOUGH usernames.");
clearInterval(scrollPage);
printUsernames();

How do I use data out of chrome.storage.get function?

I'm trying to grab data from chrome extension storage, but I can use them only in this function.
var help = new Array();
chrome.storage.local.get(null, function(storage){
//get data from extension storage
help = storage;
console.log(storage);
});
console.log(help); // empty
Result in console:
content.js:1 content script running
content.js:11 []
content.js:8 {/in/%E5%BF%97%E9%B9%8F-%E6%99%8F-013799151/: "link", /in/adam-
isaacs-690506ab/: "link", /in/alex-campbell-brown-832a09a0/: "link",
/in/alex-davies-41513a90/: "link", /in/alex-dunne-688a71a8/: "link", …}
Async function has won. I wrote my code again and now function is called hundreds time, i can not do this in dirrefent way
code:
console.log("content script running");
var cards = document.getElementsByClassName("org-alumni-profile-card");
var searchText = "Connect";
function check(exi, cards) {
chrome.storage.local.get(null, function(storage) {
for (var key in storage) {
if (storage[key] == "link" && key == exi) {
cards.style.opacity = "0.3";
}
}
});
}
for (var i = 0; i < cards.length; i++) {
var ctd = cards[i].getElementsByClassName(
"org-alumni-profile-card__link-text"
);
var msg = cards[i].getElementsByClassName(
"org-alumni-profile-card__messaging-button-shrunk"
);
if (ctd.length < 1 || msg.length > 0) {
cards[i].style.display = "none";
} else {
var exi = cards[i]
.getElementsByClassName("org-alumni-profile-card__full-name-link")[0]
.getAttribute("href");
check(exi, cards[i]);
}
}
SOLUTION of my problem
I wanted to delete this topic, but I can not, so instead of doing that, I'll put here what I've done finally.
The code above is wrong becouse, it was taking a list of links from website and for each from them script was grabbing a data from a storage... Which was stupid of course. I didn't see a solution which was so easy:
Put all your file's code in this function - it grabs data from storage just once.
I'm so sorry for messing up this wonderfull forum with topic like this.
Hope u'll forgive.
help will return undefined because it is referencing a asynchronous function and not the return value of that function. The content from storage looks to be printed on content.js:8, i.e. line 8.

How do I use a variable in this function?

I've got this problem i can't solve.
I want to make the part that says "aboutMe" a variable called page_name (after the parameter), but I can't get it working...
$(document).ready(function(page_name) {
$.getJSON('../json/text.json', function(obj) {
// fill the title
for(i in obj.titles) {
var id1 = obj.titles[i].id;
var title1 = obj.titles[i].title;
$("#"+id1+"_title").append(title1);
}
// fill the rest of the page
for(i in obj.pages.aboutMe.page_element) {
var id = obj.pages.aboutMe.page_element[i].id;
var title = obj.pages.aboutMe.page_element[i].title;
var content = obj.pages.aboutMe.page_element[i].content;
var left_content = obj.pages.aboutMe.page_element[i].content_left;
var right_content = obj.pages.aboutMe.page_element[i].content_right;
$("#"+id+"_title").append(title);
$("#"+id+"_content").append(content);
$("#"+id+"_left_content").append(left_content);
$("#"+id+"_right_content").append(right_content);
}
for(var i in obj.pages.study) {
}
});
});
Does Anyone know how to solve this?
I would be very gratfull!
What is the error? Try using $(document).ready(function(){}); syntax. It may happen that there is a Jquery conflict. You can also resolve that by JQuery(document).ready(function(){});

JavaScript Find Specific URLs.

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
}
}

How to run a setInterval that loops and tries a max of 10 times before breaking?

I have the following to try to reload on a connection drop:
setInterval(window.location.reload(), 1000);
My concern with this is that it could continue forever, ddos'ing my application.
How can I update the above to try at max 20 times before giving up and breaking?
Thank you
This makes me feel dirty, but you could update/extract the window hash with each refresh:
function hack () {
var last = parseInt(location.hash.slice(1));
if (last < 20) {
window.location.hash = last + 1;
window.location.reload();
}
}
window.location.hash = 0;
setTimeout(hack, 1000);
You need to persist some counter state from one page load to the next so you can know when 20 reloads have been done. Your options are:
A hash value
A query parameter
A cookie value
Something stored in local storage
If you don't need this value to persist beyond just the reloads of this page, then options 1) and 2) are better as they are only as persistent as you need. A hash value will not be sent to your server, but could interfere with other uses of the hash value. A query parameter would be sent to the server, but any reasonable server will ignore query values it doesn't know and it won't interfere with anything else. I'd probably pick a query parameter and have actually used one to avoid infinite redirection loops in some of my code. You could implement option 2) like this:
function checkAutoReload() {
var currentCnt = 0;
var re = /(\?|&)(reloadCnt=)(\d+)/;
var param = window.location.search.match(re), newURL;
if (param) {
currentCnt = parseInt(param[3], 10);
newURL = window.location.href.replace(re, "$1$2" + (currentCnt + 1))
} else {
newURL = window.location.href;
newURL += window.location.search ? "&" : "?";
newURL += "reloadCnt=1";
}
if (currentCnt < 20) {
window.location.replace(newURL);
}
}
setTimeout(checkAutoReload, 1000);
Notice, there's no need for a setInterval() because a given page's code only runs once before it either reloads or finds that it is done reloading.
Store the reloadCount in localStorage
MDN DOM Storage
var maxReload = 20;
var reloadPage = function() {
if (typeof a !== "undefined" && a !== null) {
console.log(localStorage.reloadCount);
localStorage.reloadCount = 0;
};
var reloadCount = parseInt(localStorage.reloadCount, 10);
console.log(reloadCount);
if (reloadCount < maxReload) {
reloadCount += 1;
localStorage.reloadCount = reloadCount;
// RELOAD CODE HERE
};
};
// call reloadPage from your code
reloadPage();

Categories

Resources