I have the code below that fetches images from a directory and displays in HTML. The images in this directory constantly change every second. It works somewhat on desktop browsers, but I cannot make it work on mobile browsers. It seems that it's always reading the cached images rather than reloading from the server. It can work by hitting ctrl+F5 on desktop browsers, but not on mobile browsers. Is there a way to hard refresh a mobile browser (chrome) via JavaScript?
<html>
<head>
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<img id="viewer" src="" width="100%"/>
<div id="info"> </div>
<button id="btnLeft" type="button">Left</button>
<button id="btnRight" type="button">Right</button>
<input type="button" value="Refresh page" onclick="location.reload(true);" />
<script>
$(function() {
var baseUrl = "./Cam01/";
var pictureIndex = 0;
var pictures = [];
function getFiles() {
$.ajax(baseUrl).success(function(data) {
pictures = [];
$(data).find("a[href]").each(function() {
var href = $(this).attr('href');
if (href.indexOf('.jpg') > 0 || href.indexOf('.png') > 0 || href.indexOf('.jpeg') > 0) {
pictures.push(href);
}
});
console.log(pictures.length + " pictures loaded!");
changePicture(0);
});
}
function changePicture(indexOffset) {
pictureIndex += indexOffset;
if (pictureIndex >= pictures.length) {
pictureIndex = 0;
} else if (pictureIndex < 0) {
pictureIndex = pictures.length - 1;
}
$('#viewer').attr('src', baseUrl + pictures[pictureIndex]);
$('#info').text((pictureIndex + 1) + "/" + pictures.length);
}
getFiles();
$('#btnLeft').click(function() {
var left = -1;
changePicture(left); return false;
});
$('#btnRight').click(function() {
var right = 1;
changePicture(right); return false;
});
$(document).keydown(function(e){
var left = -1, right = 1;
if (e.keyCode == 37) {
changePicture(left); return false;
} else if (e.keyCode == 39) {
changePicture(right); return false;
}
});
});
</script>
</body>
</html>
One method to prevent loading an image from cache is to append a timestamp to its URL.
This causes the resource to seem "fresh" because it's different from the last time it was loaded.
I prefer using the "file modified" timestamp so that only images that have changed since the last load are refreshed. Images that haven't changed could be loaded from cache. But, it seems you're parsing a directory index page and that timestamp isn't available to you.
You can append the current timestamp to the URLs to prevent caching. But as #Ajaypayne alluded, this could cause unnecessarily high bandwidth use because it prevents caching even if an image hasn't changed.
Something like this:
var href = $(this).attr('href') + '?'+Date.now();
Edit
Actually, since images are loaded upon button press, I would add the timestamp inside the changePicture() function instead of on page load:
$('#viewer').attr('src', baseUrl + pictures[pictureIndex] + '?'+Date.now());
Edit
Incidentally, jQuery's .ajax() function accepts a cache parameter for GET requests:
cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
So maybe:
$.ajax({
url: baseUrl,
method: "GET",
cache: false
}).done(function(data) {
// process data here
});
Related
I have a code that inserts a popunder into all the links on my page.
However, I need something that makes this popunder / tabunder run automatically, regardless of the click.
I've tried in many ways but I can't.
Can someone help me?
window.onload = function() {
var puURL = 'http://google.com';
var puTS = Math.round(+new Date()/1000);
console.log('T.'+localStorage.puTS+'/'+puTS);
if (typeof localStorage.puTS == 'undefined' || parseInt(localStorage.puTS) <= (puTS - 3600)) {
var links = document.getElementsByTagName('a');
for(var i = 0, len = links.length; i < len; i++) {
links[i].onclick = function (e) {
var puHref = this.getAttribute("href");
var puTarget = this.getAttribute("target");
if (puHref !== '#' && puHref !== 'javascript:void(0)') {
e.preventDefault();
if (puTarget == '_blank') {
window.open(window.location.href);
}
window.open(puHref);
window.location.href = puURL;
localStorage.puTS = puTS;
}
}
}
}
};
I have placed your script locally under the HEAD Tag section and the function is triggered when I open the HTML file. I assume that the issue lays in the script placement.
If your script is stored outside the project (is external), make sure that you navigate to the correct root and double-check for spelling. Here is an example:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="project/javascript_folder/myscript.js"></script>
</head>
<body>
...
</body>
</html>
You can check out W3Schools File Paths for more detail.
If you open your browsers DEV-TOOLS (by pressing the Right-Click button on your mouse while you hover over the page) and navigate to the console section, you should see the successful output from your function:
In my case, it is T.undefined/... where "..." represents a randomly generated number in the length of 10.
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>
I've inherited a site that calls a javascript on every page to prepend every external link with a link to an exit page. On exit.html, a function in the same script (confirmExit) extracts the original intended url, and that’s served up as a link on the page by ID (<p>Continue to:</p>)
Now, instead of the user having to click on exitLink, an automatic redirect with a delay is wanted. Something like "You will now be taken to exitLink in 10 seconds …"
I’ve seen the setTimeout approach, the <META HTTP-EQUIV="refresh" CONTENT="seconds;URL=the-other-url"> approach, and even a form approach for achieving automatic redirects. Problem is, those seem intended for hard-coded, page-specific redirects. I haven’t been able to figure out how to adapt any of these to the js or the exit.html page to make them work. Sorry, I'm still low enough on the javascript learning curve that I can't seem to find the forest for the trees!
Any solution would be greatly appreciated! (Except php - I can't use that)
Here’s the javascript:
window.onload = function() {
wrapExitLinks();
}
function wrapExitLinks() {
var whiteList = "^gov^mil^";
var exitURL = document.location.protocol + "//" + document.location.host + "/exit.html"; // Default exit is /exit.html from referring site
var currentBaseURL = document.location.protocol + "//" + document.location.hostname + document.location.pathname;
var links = document.getElementsByTagName("a");
var linkDest;
var linkTLD;
var govTLD;
/* Do not wrap links on intersitial exit page */
if (currentBaseURL != exitURL) {
for (var i in links) {
if (links[i].host) {
linkTLD = links[i].hostname.substr(links[i].hostname.lastIndexOf(".") + 1); // Extract top level domain from target link
linkDest = links[i].href;
if (whiteList.indexOf("^" + linkTLD + "^") == -1) {
linkDest = exitURL + "?url=" + encodeURIComponent(linkDest);
links[i].href = linkDest;
}
}
}
} else {
confirmExit();
}
}
function confirmExit() {
var queryString = decodeURIComponent(document.location.search.substr(1));
var linkDest = queryString.substr(queryString.indexOf("url=") + 4);
var exitLink = document.getElementById("exitLink");
/* Assume http:// if no protocol provided */
if (linkDest.indexOf("://") == -1) {
linkDest = "http://" + linkDest;
}
exitLink.href = linkDest;
exitLink.innerHTML = linkDest;
}
The basic script you need is simply:
setTimeout(function () { window.location = 'http://example.com'; }, 10000);
That's all. Work it into your script somewhere.
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() );
I have an iFrame that is running some Javascript and I want the iFrame to behave differently depending on which page it is loaded into. I found this code which works brilliantly but it shows me the url of the iFrame not the parent.
var Page1 = "page1.html";
var Page2 = "page2.html";
var thisUrl = decodeURI(window.location);
var urlChunks = thisUrl.split("/");
for (var chunk in urlChunks) {
alert('chunk: ' + chunk);
alert('urlChunks[chunk]: ' + urlChunks[chunk]);
if (urlChunks[chunk] == Page1) {
alert('inside index.html');
}
else if (urlChunks[chunk] == Page2) {
}
else
{
}
}
What can I change the
decodeURI(window.location);
to in order to get it to read from the parent.
window.parent.location
Remember that JavaScript has the Same-Origin restriction, so when the parent document is a different origin (eg. domain), you will most probably get an access-denied exception.