execute script on the page that will open by clicking href javascript - javascript

I am currently working on features that infuencent web loading. I succeeded
to find a script that displays those .But my problem how to execute this script on the page that will open by clicking href
<html>
<head>
<script type="text/javascript">
// Add load event listener.
window.addEventListener("load", loadTime, false);
function loadTime() {
var x = performance.timing.connectEnd+"f";
// Get current time.
var now = new Date().getTime();
// Calculate page load time.
var page_load_time = now - performance.timing.navigationStart;
// Write the load time to the F12 console.
if (window.console) { console.log(window.performance.timing);
window.alert(x)}
}
</script>
<script>
var someAnchor = document.getElementById('someAnchor');
someAnchor.onclick = function(){
loadTime();
};
function loadTime() {
// Get current time.
var now = new Date().getTime();
// Calculate page load time.
var page_load_time = now - performance.timing.navigationStart;
// Write the load time to the F12 console.
if (window.console) {
console.log(window.performance.timing);
}
}
</script>
</head>
<body>
<a id="someAnchor" target="_blank" href="https://www.youtube.com/">youtube</a>
</body>
</html>
The first script shows these carachteristics on current page but the second does not work on load youtube page

so you basically just want to run your function upon clicking an anchor?
var someAnchor = document.getElementById('someAnchor');
someAnchor.onclick = function(){
loadTime();
};
function loadTime() {
// Get current time.
var now = new Date().getTime();
// Calculate page load time.
var page_load_time = now - performance.timing.navigationStart;
// Write the load time to the F12 console.
if (window.console) {
console.log(window.performance.timing);
}
}
<a id="someAnchor" href="#">some anchor</a>

What you want to do is illegal and impossible, because of security reasons, once you close a page or navogate away from it, every javascript function will stop immedialitely. Just imahine what would happen, if a page would navigate you back every time you leave it.

Related

Displaying Page Load Time On Webpage

I want to display the loading time of a webpage on site. I can get this working by writing to console.log but writing the information to a page is beyond me.
In my head I have
<!-- Loading Time -->
<script type="text/javascript">
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
</script>
Then I have this to write to the console log
<script type="text/javascript">
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime / 1000);
}
</script>
This works perfectly but I really want to display the loading time on a webpage. How do I achieve this? My page is a simple html / css site.
Three possible methods are:
Just writing to the document directly (should not be used because of the reasons described here):
document.write(loadTime);
Adding an HTML element and setting its inner text to loadTime:
function displayLoadtime(loadtime){
document.getElementById("loading-time").innerText = loadtime;
}
<p id='loading-time'>Loading...</p>
Creating the element in Javascript and displaying the loadTime using it:
function displayLoadingtime(loadtime){
let p = document.createElement("p");
p.innerText = loadtime;
document.getElementById("loading-time-container").appendChild(p);
}
<div id='loading-time-container'></div>
I know what I answered is some beginners' stuff and you probably know it, but I will edit the answer in case you give more details, because I don't see any problems in displaying it if you already have the loadTime.
You can write the time you calculated into an element of the webpage using the innerText property of a Node.
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log('Page load time is ' + loadTime / 1000);
performanceDisplay = document.getElementById("performance-display") // get a reference to the paragraph
performanceDisplay.innerText = loadTime / 1000 // put the value of the variable loadTime into the paragraph
}
<body>
<p id="performance-display"></p>
</body>
Or, if you do not want to put the paragraph manually into the HTML, you can create it in the JavaScript using document.createElement:
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log('Page load time is ' + loadTime / 1000);
performanceDisplay = document.createElement("p") // create a new paragraph element
performanceDisplay.innerText = loadTime / 1000 // put the value of the variable loadTime into the paragraph
document.body.appendChild(performanceDisplay) // add the paragraph element to the body of the document
}
Welcome to StackOverflow, Rylad!
You can easily put it into your webpage by referencing an HTML element.
Ie. add an element with the id timeContainer to your page and set its innerHTML to your variable, loadTime. Here's an example:
<body>
<span id="timeContainer">
The load time will be displayed here when the page is finished loading
</span>
<script type="text/javascript">
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log(loadTime)
document.getElementById("timeContainer").innerText = loadTime;
}
</script>
</body>
Try this,
Simple way to get loading time
<body>
<span id="loadingTime"></span>
<script>
window.addEventListener('load', (e) => {
let timestemp = new Date(e.timeStamp).getTime()
console.log('loading time is', timestemp)
document.getElementById('loadingTime').innerText = "loading time is "+timestemp
})
</script>
</body>

Calling function from current tab in a new tab

I wrote the following code:
function challenge() {
var body = $("body").html();
if(body.match(/td\>([0-9]+)\<\/td\>/)[1] > 0){
// find challengable player
var url = body.match(/href="(\/game.php?.*challenge.*[0-9a-f]+)"/)[1].replace(/&/g, '&');
// open new tab with the link
var winEvent = window.open(url, '_blank');
// get random number between 7 and 10
var rand = Math.random() * (10 - 7) + 7;
// set interval for new tab to random minutes
winEvent.setInterval(challenge, rand*1000);
// close current tab
window.close();
}
}
window.setInterval(challenge, 5*1000);
In challenge() I look for a link and open it in a new tab. However, the following line is not working as intended:
winEvent.setInterval(challenge, rand*1000);
The new tab should call the challenge() function every rand seconds
Thanks in advance!
Okay, based on your comment and given code. I am still a lil confused. But from what I understood here that you want to open a new tab and in that new tab you want to open another new tab.
Here is a generic solution. You can change it according to your needs.
To test it in a fiddle you need to allow your popup blocker and ad blocker.
<html>
<body>
<div>
hello
</div>
<script>
function openTab() {
var newWindow = window.open(); //CREATE A NEW TAB
//WRITE CURRENT OUTER HTML TO THE NEW TAB (BASICALLY CLONING THE CURRENT TAB)
newWindow.document
.write(document.getElementsByTagName("html")[0].outerHTML)
window.close();
}
setTimeout(() => {
openTab();
}, 1000); //OPEN TAB AFTER 1 SECOND
</script>
</body>
</html>
NOTE: This is not a good design or structure, as popup blockers or ad blockers will block your new tab opening. According to me, I wouldn't recommend doing something like this.

Chrome Extension - setInterval stopping when popup.html closed

I'm trying to build my first simple Chrome Extension and I'm new to Javascript, so I hope you can help me.
My extension has only one goal: creating a Google Rich Notification every X Seconds/Minutes. The Value for X comes from an Input textfield from a popup.html. I'm using the setInterval-Method for repeatedly creating a notification.
You can see the popup.js and popup.html below.
popup.js:
var NotOptions = {
type : "image",
title: "In die Ferne gucken!",
message: "Nur auf den Bildschirm zu starren, ist nicht gesund",
expandedMessage: "",};
var timeElement = document.getElementById("time");
var timeValue = null;
var time = null;
var interval = null;
timeElement.onchange = getTimeValue;
function getTimeValue() {
timeValue = timeElement.value * 60000;
localStorage.setItem("timeValue", timeValue);
activateReminder();
}
function activateReminder() {
time = localStorage.getItem("timeValue");
clearInterval(interval);
if(time >= 3000 && time <= 1800000) {
interval = window.setInterval(function() {
doNotify();
console.log("Time is " + time);
}, parseInt(time));
}
}
function doNotify() {
var path = "/images/eye127.png";
var options = null;
options = NotOptions;
options.iconUrl = path;
options.priority = 0;
options.imageUrl = chrome.runtime.getURL("/images/tahoe-320x215.png");
chrome.notifications.create(options);
}
popupt.html:
<html>
<head>
</head>
<body>
<h1>Watch out!</h1>
Time in minutes:<input type="text" id="time">
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
My problem is that it will only work as long as the popup.html stays open. As soon a it gets closed, setInterval stops working.
But when I simply do following code in my popup.js I get a Noticifation every 6 seconds even when popup.html is closed. Here is the problem that I have a fix value for 6 seconds. Instead I want to use the value from the input field.
setInterval(function() {
doNotify();
console.log("Time is " + time);
}, 6000);
Now I want to do 2 things:
pass value from inputfield from the popup.html to the setInterval-method
setInterval should keep running with the value specified in the inputfield even when the popup.html closes
How can I achieve that?
Here link to my github-repo if you want to checkout project
blink-reminder
thank you in advance
A better way to do it is to move the "clock code" to a background page.
This will allow you to run a code without any opened popup.
The popup will only be here to set the number of second between each execution of your clock. For this you can use the local storage like you've done in your code, or use the Messaging API of Chrome Extensions.
If you use local Storage, you can use the onChanged event to synchronise the background with the changement of value in the popup.
Here more informations about background pages
Here more informations about Messaging API
Here more informations about local storage (onChanged event)

run a Js script bot every time that a page is loaded

i'm new in firefox add-on dev
I'm triyng to run a contentscriptScript in a active tab which click on a random link into the tab, it's works
But i'm trying to repeat this operation in the new webpage in an endlessly way, like a kind of WebBot.
i dont know if i have to implement this setting in the contentScript or in the Main.js , SetInterval and SetTimeOut seems to doesnt work.
Here the ContentScript.
var webs = []; // all links
var l = document.links; //get all links
var unwebs; //new WebPage
function browse(){
// find links
for(var i=0; i<l.length; i++) {
webs.push(l[i].href);
}
//pick a random link
unwebs = webs[Math.floor(Math.random()*webs.length)];
}
function clickLink(){
//redirection
window.location.href = unwebs ;
}
$(document).ready(function(){
browse();
clickLink();
}
thank you.
See the tabs docs
main.js
var tab = require('sdk/tabs').activeTab;
tab.on('ready', function() {
//attach content script with tab.attach
});

Splash Page Video (jQuery Hide) Reveal Index Underneath Issue

I need to have a splash page, but I don't want to make it my index, so I am using this solution.
I am using this technique:
http://jsfiddle.net/JjvzT/
on this page:
http://www.kineticoriginsofrhythm.com/
But I cant get the "Enter" button to reveal the index page below. Any Suggestions? It just flickers and jumps back to the Video Splash Page.
Also whats the js cookie code that makes it only appear once per day?
Thank You Very Much.
Also, if you can save your "anti-Splash" debates for another time that would be great. Client "MUST HAVE" this splash page. Not my idea.
Change the href attribute for your "Enter" anchor to "#". Right now you are redirecting them to the same page after hiding the splash, which is forcing them to load the page in its initial state again.
EDIT: For the cookie,
jQuery(function(){
if(document.cookie.indexOf("firstvisit") != -1){
$("#splash").hide();
$("#container-index").show();
}
else{
$("#splash span").click(function() {
$("#splash").hide();
$("#container-index").show();
var expireDate = new Date();
/* sets expire date to current date + 1 day */
expireDate.setDate(expireDate.getDate() + 1);
var newCookie = "firstvisit=0;expires=" + expireDate.toUTCString();
document.cookie = newCookie;
});
}
});
Caveat: I haven't tested this. See here for more on JavaScript and cookies: http://www.w3schools.com/JS/js_cookies.asp
I took ZDYN's answer and created splash.js, which can simply be added to your splash page (not a hidden div) and to the page that you want to redirect from, ie. index.html or something.
Anyway, here's the commented, working code:
/*
1. Create a separate html page to be the splash page
2. Out a referrence to this script in the splash page
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
3. Put a reference to this script in every page that you want to have the splash page appear on
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
4. Set the "splashPageName" below to the file name of the splash page
5. Set the date variables below
*/
var splashPageName = "splash.html";
var endSplashDate = new Date("12/7/2011");
var expireCookieDate = new Date();
(function() {
var url = window.location.toString();
if (url.toLowerCase().indexOf(splashPageName) >= 0) {
/* sets expire date to date + 1 day */
expireCookieDate.setDate(expireCookieDate.getDate() + 1);
var newCookie = splashPageName + "=0;expires=" + expireCookieDate.toUTCString();
document.cookie = newCookie;
}
else {
if (document.cookie.indexOf(splashPageName) != -1) {
//stay here, they've already seen the splash page
}
else {
var today = new Date();
if (endSplashDate > today) {
window.location = splashPageName;
}
}
}
} ());
Try this
$(document).ready(function(){
$("#splash").click(function() {
$(this).hide();
$("#container-index").show();
});
});

Categories

Resources