Javascript redirect infinite loop - javascript

Chrome is not redirecting to an intranet site. The body onload method is looping infinitely. If I change the target to an external website such as google.com, the redirection works. Can someone give pointers to find why is there an infinite loop for my intranet site?
Below is my HTML
<!DOCTYPE HTML>
<script type="text/javascript" src="openBrowser.js"></script>
<script type="text/javascript">
function openURL(){
var targetURL="http://myintranetsite";
openBrowser(targetURL);
}
</script>
<BODY onLoad="openURL()">
<div id="loadBrowser"><h1>Opening Browser..</h1></div>
</BODY>
</HTML>
my javascript
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(isChrome)
{
//Changes the URL to destination if the current chrome browser version is 40
if(getChromeVersion()>=40)
{
window.location=targetURL;
}
}

your code must be redirecting for chrome version 40 or higher, you must see that you are not already in the place where you want to go, causing infinite redirection. Here is the code that can work for you
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(isChrome)
{
//Changes the URL to destination if the current chrome browser version is 40
if(getChromeVersion()>=40 && window.location!==targetURL)
{
window.location=targetURL;
}
}

Check that window.location isn't your intranet page
if (window.location.hostname.indexOf("myintranetsite") > -1) {
openBrowser(targetURL);
}
Alternatively maybe hit the brakes a little later:
if (window.location.toString() != targetURL && getChromeVersion()>=40) {
window.location=targetURL;
}

Related

Popunder run automatically

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.

Fetch and view images html

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

Reading iframe content doesn't work under Chrome

I need to use a content of a .txt file on a web page. The problem is that I can't do it easy way (server-side php). I figured out the trick of opening a text file in the iframe and then asking for innerHTML/innerText. It turns out that people were there before - found the following code, much cleaner than my attempts, at https://zipcon.net/~swhite/docs/computers/browsers/extern_via_iframe.html
It works locally under FireFox and IE, but does not under Chrome. How to make it work under Chrome?
function getIframeContentText( frameID )
{
var elt = document.getElementById(frameID);
//alert( "getIframeContentText:" + elt );
//alert( "getIframeContentText Content:" + elt.contentDocument );
if( elt.contentDocument ) // DOM
{
var iframe_doc = elt.contentDocument;
var range = iframe_doc.createRange();
range.selectNodeContents( iframe_doc.body );
return range.toString();
}
else // IE6
{
var iframe_doc = document.all[frameID].contentWindow.document;
//return iframe_doc.body.innerHTML; // gets HTML
return iframe_doc.body.outerText;
}
}
This is because handling iFrames in ie and firefox is differentthan chrome ,because of chromes same-origin policy
start the browser using chrome.exe --user-data-dir="." --disable-web-security
and you have to wait for the document to load fully ie all the contents of the page ,it may happen there may be iFrame inside iFrame (for generic solution )
$(window).load(function()
{
chromeFrameInitializers(document);//for handling frames and IFrames
});
function chromeFrameInitializers(document)
{
var frame=document.getElementsByTagName("frame");
for(var i=0;i<frame.length;i++)
{
var subDocFrame=frame[i].contentDocument;
//do your stuf
chromeFrameInitializers(subDocFrame)
}
var iFrame=document.getElementsByTagName("iFrame");
for(var i=0;i<iFrame.length;i++)
{
var subDocIFrame=iFrame[i].contentDocument;
//do your stuf
chromeFrameInitializers(subDocIFrame)
}
}
`
it handles for both frame and iFrame (recursively ). for this $(window).load jquery needed

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.

Print external page without open it

I want print a page without open it on all major browsers. (Safari, IE, firefox, Chrome and Opera)
I tried that but doesn't work on firefox (Error : Permission denied to access property 'print') :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<link rel="alternate" media="print" href="print.php">
<script type="text/javascript">
function impression() {
window.frames[0].focus();
window.frames[0].print();
}
</script>
</head>
<body>
<iframe height="0px" src="print.php" id="fileToPrint" style="visibility: hidden"></iframe>
Imprimer
</body>
</html>
This code works on Chrome.
I want one thing like that for all browsers to mention but I don't know how.
Is there another way to do that?
Create an iframe, hide it, and then call the proper print functions. The execCommand should work for all versions of IE.
Mind you: $.browser won't work for newer versions of jQuery and should be avoided. Use your preferred way of detecting features.
var ifr = createIframe();
ifr.hide();
if ($.browser.msie) {
ifr.contentWindow.document.execCommand('print', false, null);
} else {
ifr.contentWindow.focus();
ifr.contentWindow.print();
}
This was developed for IE, FF and Chrome. I have no idea how well this will work for Safari and Opera, but it might give you some ideas.
Edit: as adeneo correctly pointed out, $.browser is deprecated and should be avoided. I updated my statement. I'll leave my code untouched, as it still expresses the correct intent.
You can try this code, but it's Javascript ;
<script language="JavaScript">
var gAutoPrint = true; // Tells whether to automatically call the print function
function printSpecial()
{
if (document.getElementById != null)
{
var html = '<HTML>\n<HEAD>\n';
if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}
html += '\n</HE>\n<BODY>\n';
var printReadyElem = document.getElementById("printReady");
if (printReadyElem != null)
{
html += printReadyElem.innerHTML;
}
else
{
alert("Could not find the printReady function");
return;
}
html += '\n</BO>\n</HT>';
var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint)
printWin.print();
}
else
{
alert("The print ready feature is only available if you are using an browser. Please update your browswer.");
}
}
</script>

Categories

Resources