load different urls one by one after certain delay - javascript

Hi I have a array of urls which I want to load in the same browser window one by one. For now I am able to load a single url in a browser window using
window.location = url;
But when I put this window.location in a function and call that function infinitely in a loop with some delay the page just keeps on loading and nothing gets displayed. Code is below:
<html>
<head>
<script>
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var i = 0;
function redirect_url(url)
{
window.location = url;
}
while (true)
{
setTimeout(function() { redirect_url(urls[i]); }, 5000);
// update the index
i = (i + 1) % urls.length;
}
</script>
</head>
What I want is when I open this script file in my browser then the first url's webpage should get loaded and after 5 secs second url's webpage should get loaded and this should continue infinitely.

Here is a method without the While loop; Seems to work well on my end: http://jsfiddle.net/77617znz/2/
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var i = 0;
function redirect_url()
{
if( i <= urls.length )
{
setTimeout(function(){
$('iframe').attr('src', urls[i]);
i++;
redirect_url();
}, 3000);
}
}
redirect_url();
Hope this helps! Let me know if you have any questions.

window.location = url; will load the page with full refresh. Once that happens all the script from the previous page will not be available so what you are trying the achieve will never happen.
May be you can have an iframe on the page and change the iframe source every 5 seconds as you need.
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function () {
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var i = 0;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 5000);
loadIframe(urls[i]);
});
</script>
</head>
<body>
<iframe id="iframe" height="100%" width="100%"></iframe>
</body>
</html>
Demo http://plnkr.co/edit/hjx3b234MUDzkSL67RW5?p=preview

I don't think what you're trying to achieve can be done by the code you have posted. If you set the location it will navigate to the new page and your JavaScript will cease to function.
You could try using some other systems such as IFRAMES or ajax requests to load and render them on your page. This will lead to issues where the Origin of your page will not match the one you are loading. This will throw an error and the page will fail to load.
For the IFRAMEs the X-Frame-Options of the page you are loading will prevent it from being displayed. Also if your page is HTTPS and the other page is not it will also fail to load.

Expanding on ShankarSangoli's answers since original code will not work. Looping through and doing the set timeout as 5000 will just load those urls simultaneously 5000 seconds from now. You need to increment that value.
<html>
<head>
<script>
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var timeout = 5000;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
for (var i = 0; i < urls.length; i++)
{
setTimeout(function() { loadIframe(urls[i]); }, timeout*i);
}
</script>
<iframe id="iframe" height="100%" width="100%"></iframe>

Related

JavaScript Reload Function Not Working Properly

On my webpage I have a piece of JavaScript to reload/refresh an iframe every three seconds.
window.setInterval(function() {
reloadIFrame()
}, 3000);
function reloadIFrame() {
var frame = document.getElementById("iframe");
var len = frame.getElementsByTagName("TABLE").length;
if ( len == 0 ){
console.log('reloading..');
document.getElementById('iframe').contentWindow.location.reload();
}
}
However, I don't want the function to work when there is a table present in the iframe, and it still runs when there is a table. Please let me know if there is something I am missing or your suggestions for alternative solutions.
(I do believe that the iframe which I am referencing is local on localhost:8000. I'm working with Django, if that matters, and this is part of a template.)
For anyone with a similar problem:
As in charlietfl's comments on the original post, the contentWindow was not being referenced. My code as modified below works now:
window.setInterval(function() {
reloadIFrame()
}, 3000);
function reloadIFrame() {
var frame = document.getElementById("iframe");
var len = frame.contentWindow.document.getElementsByTagName("TABLE").length;
if ( len == 0 ){
console.log('reloading..');
document.getElementById('iframe').contentWindow.location.reload();
}
}
I simply needed to add contentWindow.document after frame.

Refresh an iframe automatically in AJAX

I have a simple iframe that I want to refresh every 5 seconds, without clicking somewhere or doing something at all
<iframe src="my-messages.php">
They want the user to click somewhere, I do not. I want this as an automatic process.
Here's a way to do it, though if the user is doing anything within the iframe they will lose their progress.
window.setInterval(function() {
document.querySelector('iframe.reload').setAttribute('src', 'https://freesecure.timeanddate.com/clock/i5sso5fg/n1328/tluk');
}, 5000);
<iframe class="reload" src="https://freesecure.timeanddate.com/clock/i5sso5fg/n1328/tluk" frameborder="0" width="57" height="18"></iframe>
The simplest way is to use the refresh meta tag. Just add this to the head section of my-messages.php...
<meta http-equiv="refresh" content="5" />
Alternatively, add this to my-messages.php in order to do the same thing with Javscript...
<script>
setTimeout(function() {
window.location.reload();
}, 5000);
</script>
Use javascript to change the src of the iframe to "my-messages.php" again. This is a solution using JQuery to select the element.
<iframe src="my-messages.php" id="frame">
in your JS
var refreshMS = 10000;
var $frame = $('#frame');
var timeoutFunction = function(){
$frame.attr("src", "");
$frame.attr("src", "my-messages.php");
setTimeout(timeoutFunction, refreshMS);
};
setTimeout(timeoutFunction, refreshMS);
This basically sets the src element every 10 seconds, causing the iframe to reload its contents.
Edit: As recommended, non-jquery version
var refreshMS = 10000;
var frame = document.getElementById("frame");
var timeoutFunction = function(){
frame.setAttribute("src", "");
frame.setAttribute("src", "my-messages.php");
setTimeout(timeoutFunction, refreshMS);
};
setTimeout(timeoutFunction, refreshMS);

script to detect adblock isn't working

Can someone please help me with this script? It is to detect adblock. I have <script src="/js/ads.js"></script> in the head (a empty ads.js in the folder). Adblock will block this from loading thus not being on the page. Then I have the code below that will detect if the script is loaded or not. For some reason it is not working properly and still displays images. I had someone write the script below as well for it to check for ads 3 times with a 1 second interval but it seems to check infinitely 3 times at once. Can someone please help me work this properly? And also if it detects that it does load properly it won't keep pasting images into the div?
<script>
$(document).ready(function () {
var count = 3;
for (var i = 0; i < count; i++) {
setInterval(function () {
if (window.canRunAds === undefined) {
$('#StEQBidTjU').prepend('<img src="/miscimg/mZKoARJXcF.jpg" id="PtZZtkYjaR" />')
$('#AbHPbbbxyl').prepend('<img src="/miscimg/6hZ4nqcBZd.jpg" id="PLyCMzOHpx" />');
}
}, 1000);
}
});
</script>
You need to keep track of the count in each interval, and clear it once it's ran 3 times.
$(document).ready(function () {
var count = 3,
interval = setInterval(function () {
if (--count < 0) {
clearInterval(interval);
}
if (window.canRunAds === undefined) {
$('#StEQBidTjU').prepend('<img src="/miscimg/mZKoARJXcF.jpg" id="PtZZtkYjaR" />')
$('#AbHPbbbxyl').prepend('<img src="/miscimg/6hZ4nqcBZd.jpg" id="PLyCMzOHpx" />');
}
}, 1000);
});
Now you don't even need to do all these to detect AdBlock users, You can achieve this using a simple JS script called ABDetector
Here's how to use it:
- Download/Clone the project, upload the file abDetector.min.js
- Put this in your <head>:
<script type="text/javascript" src="abDetector.min.js"></script>
- Use this wherever you want to display a message to AdBlock users:
<div id="ab-message" style="display: none">Your message here!</div>
Then you're done. Check out the project on Github.

How do I load iframes at different time intervals like a playlist

I would like to load a bunch of iframes at different times, not all at the same time but one after another like one at 300000ms, then 209000ms, then 257000ms, etc. They will all need to be loaded at different times after each other and I need to be able to change them later if needed. I would like it to be when I click a button not as an onload event. I have little experience in javascript.
Please no jQuery.
Thanks!
Edit: I want the iframes to load on top of one another, or replace one another, not load a bunch of them in a list. I will only be putting up around 5 iframes total. Sorry for not being specific enough. Something like this, except for the time working:
<a target='page' href='http://framedsite1'>#1 (visible for 300000ms)</a>
<a target='page' href='http://framedsite2'>#2 (visible for 209000ms)</a>
<a target='page' href='http://framedsite3'>#3 (visible for 257000ms)</a>
<iframe id='page' name='page' src=''></iframe>
Except for auto playing through them all, not as a bunch of links but by being clicked on and loaded into the iframe after a set amount of time after the previous frames time has gone by, kind of like a playlist. They will all need to be displayed for different amounts of time then load the next iframe, I am emphasizing that they all will be different amounts of time.
You can use setInterval() and loop through to set the source for each iframe:
var iframes = document.getElementsByTagName("iframe"); //retrieves a NodeList of iframes
var i = 0;
var interval = window.setInterval(function(){
if(i < iframes.length){
iframes[i].src = "//example.com"; //source of the iframes
i++;
}else{
window.clearInterval(interval);
}
}, 3000); //interval to load each iframe in milliseconds
Demo
If you want to trigger it with a button click, just wrap it in a function and attach an event listener:
document.getElementById("idOfButton").addEventListener("click", function(){
var iframes = document.getElementsByTagName("iframe"); //retrieves a NodeList of iframes
var i = 0;
var interval = window.setInterval(function(){
if(i < iframes.length){
iframes[i].src = "//example.com"; //source of the iframes
i++;
}else{
window.clearInterval(interval);
}, 3000); //interval to load each iframe in milliseconds
});
Demo
<html>
<head>
<script>
var iframes;
var loadIframes = function(){
iframes = document.getElementsByClassName('custom-iframe');
for(var i=0; i<iframes.length; i++){
var iframe = iframes[i],
seconds = iframe.getAttribute('data-seconds'),
src = iframe.getAttribute('data-src');
run(i, src, seconds);
}
}
var run = function(i, src, seconds){
setTimeout(function(){
iframes[i].src = src;
}, seconds);
}
</script>
</head>
<body>
<button onclick="loadIframes()">Load iframes</button>
<iframe class="custom-iframe" data-seconds="3000" data-src="http://example.com"></iframe>
<iframe class="custom-iframe" data-seconds="900" data-src="http://google.com"></iframe>
</body>
</html>
Just change "data-seconds" and "data-src" attributes in each iframe, and put "custom-frame" class in the iframe elements.
When you click the button, they will run based on the iframe custom configs.
<html>
<head>
<script>
var buttons = document.getElementsByClassName('iframe-button');
var iframe = document.getElementById('my-iframe');
for(var i=0; i < buttons.length; i++){
var button = buttons[i];
button.addEventListener("click", function(){
var src = button.getAttribute('data-src');
iframe.src = src;
});
}
</script>
</head>
<body>
Example.com
Google.com
<iframe id="my-iframe"></iframe>
</body>
Just need to repeat those <a> elements. Put "iframe-button" class on them, and "data-src" attribute if the URL value.

Opening windows using javascript in guaranteed order

I have javascript that opens a list of URLs in their own windows. I can use window.open for each, but the problem is that sometimes, the browser doesn't always open the windows in the order I have asked them to be opened, especially when there is a large number of URLs. The URLs are not in my domain so I can't wait for an onLoad event from the child. Is there any way to determine if the child window is open before I open the next? As a last resort I guess I can create a wait time between each open, but that's more of a hack, slows everything down and while will probably make the correct order more likely, it won't guarantee it. For example:
<script type='text/javascript'>
var urls = new Array();
urls[0] = 'http://www.yahoo.com';
urls[1] = 'http://www.google.com';
urls[2] = 'http://www.facebook.com';
$(document).ready(function() {
for (i=0; i<urls.length; i++) {
window.open(urls[i]);
}
});
</script>
Okay, I figured it out. There is no way to see of a child window in a remote URL is open. That's true. However, if you open a file in your domain who's only job is to alert the parent that it's open, then redirect to the remote URL, that works. Something like this:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type='text/javascript'>
var urls = new Array();
urls[0] = 'http://www.yahoo.com';
urls[1] = 'http://www.google.com';
urls[2] = 'http://www.facebook.com';
urls[3] = 'http://www.linkedin.com';
urls[4] = 'http://www.twitter.com';
$(document).ready(function() {
var interval = null;
function doNext(i) {
if (i < urls.length) {
// console.log("Doing: " + i);
childWin = window.open('tst2.jsp?i=' + i + '&url=' + urls[i]);
interval = setInterval(function() {waitForIt(i);}, 1000);
waitForIt(i);
}
}
function waitForIt(i) {
if (document.getElementById("urls" + i).checked == false) {
// console.log('wait for: ' + i);
} else {
clearInterval(interval);
if (i < urls.length) {
doNext(i+1);
}
}
}
doNext(0);
});
</script>
<input type="checkbox" id="urls0">http://www.yahoo.com<br>
<input type="checkbox" id="urls1">http://www.google.com<br>
<input type="checkbox" id="urls2">http://www.facebook.com<br>
<input type="checkbox" id="urls3">http://www.linkedin.com<br>
<input type="checkbox" id="urls4">http://www.twitter.com<br>
then, in tst2.jsp, something like this:
<script>
opener.document.getElementById("urls" + <%=request.getParameter("i")%>).checked = true;
// console.log("Set variable");
window.location = '<%= request.getParameter("url") %>';
</script>
Also, one note, the number of windows you can open depends on the browser. Firefox can be configured to anything. It looks like Chrome is limited to 20. I'm not sure about IE.
You are probably limited in the number of windows you can open, they are probably being reused after a number of calls.
open() is supposed to be a blocking call, so it always waits until the browser has at least opened a new window before moving on to the next one.
You may try adding a random parameter as the second parameter to open to try to keep the browser from reusing windows if they were assigned default names.
// No guarantee that the name generated is unique, but if that's your only problem
// you should be OK
window.open(urls[i], "name" + new Date() + Math.random() );

Categories

Resources