A client's website has an auto-refresh feature which works great for desktop sites, but I'm making an iPhone app and need to disable it on the mobile version.
The code used is:
<META HTTP-EQUIV="REFRESH" CONTENT="30">
I would like to use javascript to disable it, if possible.
Thanks.
EDIT:
I DO NOT have access to the HTML file, and therefore can't modify it. I need to do this via code on the Objective-C side in Xcode.
I will introduce something simple
Add meta tag with ID id="meta-refresh" like this:
<meta http-equiv="refresh" content="2;http://new-url/" id="meta-refresh">
Just use these script..
var iOS = false,
p = navigator.platform;
if( p === 'iPad' || p === 'iPhone' || p === 'iPod' ){//remove which is not your target
iOS = true;
}
if(iOS){ // check if iOS then do the following
var mr = document.getElementById("meta-refresh");
mr.parentNode.removeChild(mr);
}
I believe this will work..
Also, the initiated request which JavaScript can not disable once loaded!!
For the same, the exact work around one can find in an Old Post answer given by user XP1
The above is using xmlhttp requrest (AJAX) to check before the document is loaded and remove the meta tag if the device is target device(iphone)
OR
one can use refresh dynamically id the device is not iPhone/iOS. that will remove the requirement of doing the dynamic check and requirement to avoid first refresh call. without using meta tag
var iOS = false,
p = navigator.platform;
if( p === 'iPad' || p === 'iPhone' || p === 'iPod' ){//remove which is not your target
iOS = true;
}
if(!iOS){
window.setTimeout(function(){window.location.href=window.location.href},30000); //30 Seconds
}
Assuming you are using a UIWebView to display the site, you could use [webView stringByEvaluatingJavaScriptFromString:#"..."];, where "..." is this javascript:
var metaTags = document.getElementsByTagName("META");
for(var i = 0; i < metaTags.length; i++) {
if (metaTags[i].getAttribute("HTTP-EQUIV").match(/^REFRESH$/i))
metaTags[i].parentNode.removeChild(metaTags[i]);
}
Condensed down to one line for convenience:
var metaTags = document.getElementsByTagName("META"); for(var i = 0; i < metaTags.length; i++) { if (metaTags[i].getAttribute("HTTP-EQUIV").match(/^REFRESH$/i)) { metaTags[i].parentNode.removeChild(metaTags[i]);}}
Edit: Well...after all that, turns out it's not possible to cancel an existing refresh request by simply removing the meta tag from the document. Once the parser sees the meta tag, it will refresh regardless of any javascript trickery you do. Unfortunately, the only way to overcome this is to modify the HTML page directly.
short answer: window.location.reload = () => {}
longer answer:
most browsers support some modification of a function that refreshes a web page.
the one here was tested on Chrome.
Disclaimer: this will remove the page reloading functionality entirely for a given page.
Related
I am automating a process wherein I have to login to website and download only the CSV files from the different types of files.
My jQuery code is getting executed in the console but not getting executed after integrating with HTML. Please find the jQuery code below :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).on("load", function() {
$('.ibody tr').each(function(a, b) {
var count = 0;
var name = $('.cl', b).text();
if (name.indexOf(".CSV") !== -1 && name.indexOf("TAS") !== -1) {
var d = a - 9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = window.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
window.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport¶m=" + d;
}
});
});
</script>
</head>
<body></body>
</html>
EDIT: I was, indeed, off-base with this. Didn't read your code carefully.
leaving this here for historical purposes...
I might be completely off-base with my assumptions here, and apologize in advance if this is the case. That said, it really looks like you are trying to load a page inside an IFrame and use jQuery outside of the IFrame to read data from inside the IFrame.
Long story short: you cannot use jQuery (or any javascript, or, indeed, ANYTHING AT ALL, if the browsers are working as they should) to manipulate or read content that is inside an IFrame, from outside the IFrame, if that IFrame has a src tag.
You can only manipulate / read from iframe you have built from scratch by yourself. This is by design, and for an important security reason. If you want to use IFrame to display a page, you are severely restricted to only show the page to user as-is.
If my assumption was correct, you need to either:
Get your JavaScript embedded (nicely) into the page you are now loading in your IFrame or
Use an AJAX call to get the contents of that page into your current page's memory context. This will probably mean jumping through some hoops if you really want to use jQuery to find all the elements you want.
...or, you may be able to create an empty IFrame, put the content you got from the AJAX call into that IFrame along with your Javascript, and get it to work. maybe. Not sure about this one.
can you please try with this? replace your window.createElement with document.createElement .
$(document).ready(function() {
$('.ibody tr').each(function(a, b) {
var count = 0;
var name = $('.cl', b).text();
if (name.indexOf(".CSV") !== -1 && name.indexOf("TAS") !== -1) {
var d = a - 9;
var hiddenIFrameID = 'hiddenDownloader' + count++;
var iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = "https://www.shipper-ml.com/viewReports.do?ctrl=reportListForDownload&action=DownloadReport¶m=" + d;
}
});
})
I am trying to access an element in my Edge Animate animation (which is a menu bar) from the parent document. The element has an onClick event which is triggered depending on the #bookmark in the URL of the parent web page. My code works perfectly in Firefox but does not work in Internet Explorer(10). IE is unable to see any elements within the 'Stage' div whereas Firefox can.
This is the JavaScript code on my parent page: -
<script language='javascript'>
var thisPage = window.location.pathname;
var fullurl = document.URL;
var xxx = fullurl.substring(fullurl.indexOf('#'));
var pageString = xxx.replace("#", "");
pageString = pageString.replace("http://www.mydomain.com/portfolio/photography.html", "");
if (pageString == "corporate") {
window.onload = function() {
var iframe = document.getElementById('U10511_animation');
var innerDoc = (iframe.contentDocument) ?
iframe.contentDocument : iframe.contentWindow.document;
var corporateRectangle = innerDoc.getElementById('Stage_Corporate_Rectangle');
corporateRectangle.click();
}
};
</script>
The above code will select the Corporate tab in the menu when viewed in Firefox but not IE when the URL has the suffix #corporate.
When I insert an 'alert' for the variable 'corporateRectangle' in Firefox it returns [HTMLObj] and in IE it returns 'null'.
Any ideas anyone? Thanks.
Have you tried checking the console for an error of some sort to help you and us understand the error?
IE JavaScript often works differently than in other browsers. And iframes are particularly problematical. One possibility is that you are getting the wrong document, such that the documentyou are retrieving either does not exist or does not contain the element you are looking for. So you just have to do some debugging. Here is how I would proceed. Run your script in IE.
1) Determine whether innerDoc is iframe.contentDocument or iframe.contentWindow.document. Make sure innerDoc is not null. If it is, try to get the document a different way.
2) Assuming innerDoc is not null, enumerate all of the elements in innerDoc. You can do that as follows:
for(i = 0; i < innerDoc.all.length; i++) alert(innerDoc.all [i].id);
Make sure that the id you are looking for is actually in the document. I suspect it isn't and that you need to get a different document object under IE.
I assume you are stuck with having to use iframes. If not, I suggest you use a different approach as iframes can be very problematical and browser-specific in how they work.
internet Explorer gets confused over name and id - it is highly recommended to treat these two attributes as if they were the same.
You can fix it either by 1) ensure that there are no id/name conflicts in your document, or 2)
override IE's native getElementById-method.
Read more about it here.
Ok... thanks to everyone who left suggestions.
The issue was that the menu animation has a preloader. Firefox ignores the preloader whereas IE treats the preloader as onLoad being complete. Therefore the attempt to access the element ID is null as it hasn't been loaded yet.
I decided to approach the problem from a different tack and read my bookmark from within the animation. This turned out to be a very simple solution once I figured out that I had to put the code in the first frame of the animation NOT in creationComplete or compositionReady.
This was the code: -
var bookmark = parent.window.location.hash;
bookmark = bookmark.replace("#", "");
if (bookmark == "corporate") {
sym.play("corp");
}
yes, as simple as that.
This is what I've got so far:
var x = document.getElementsByName("treeframe")[0].contentDocument.getElementsByTagName("a");
for(var idx = 0; idx < x.length; idx++){
var link = x[idx].href;
if ( link.indexOf("STRING_TO_SEARCH") != -1){
alert("found!!!");
} else {
window.setTimeout("location.reload(true);",10000);
}
}
The thing is that, after the reload when it is not found, it does not re-excecute the script.
Note: the getElementsByName is needed because I need to search in a frame inside the page, but can not acces ONLY the iframe
So you're talking about a bookmarklet? Or do you have this thing in a Frameset? If its in a frameset, and you control the frameset then you should be able to attach an event listener to the element that you are reloading. Otherwise you can probably do some form of polling using either setTimeout or setInterval to check to see if the contents of the frame are accessible.
i am trying to call a external HTML page to be displayed on website based on javascript conditions.
The code is like this
<script language="JavaScript" src="http://j.maxmind.com/app/country.js"></script>
<script type="text/javascript">
var country = geoip_country_code();
if (country == "US")
{
document.write("http://www.mywebsite.com/1.html");
}
else if (country == "GB")
{
document.write("<a href='#'><img src='http://www.image2.com' ><a/>");
}
else
{
document.write("<a href='#'><img src='http://www.image3.com' ><a/>");
}
</script>
Now, instead of showing the content of HTML page to US visitors, it just display "http://www.mywebsite.com/1.html" as plain text.
I am missing a function to call external HTML. Can someone help? Thanks
Do you mean the <iframe> element?
document.write('<iframe src="http://www.mywebsite.com/1.html"></iframe>');
Since <iframe> cannot resize itself to match the size of its content, be sure to give it a width/height attribute or style (if you know the actual size of content).
Spitting the text of a URL into a page doesn't magically grab the contents of that page. This type of activity usually happens on the SERVER where your server will fetch the content from another page and serve it up as part of YOUR page. JavaScript is the wrong tool for this job.
this kind of thing is really better to do server-side with stuff like php but here's a function I use in a lot of my commercial jobs. Again, I don't condone the use of this function for loading entire pages, but it's a really handy one to have in your toolbox. If anyone says you have to use JQuery to do this, kick them for me. ^_^
function fetchHTML(url)
{
if( 'undefined' == typeof(url) ) return false;
if( document.all ){
p = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
p = new XMLHttpRequest();
}
rnd = Math.random().toString().substring(3);
if( url.indexOf('?') > -1 )
{
url+='&rnd='+rnd;
}
else
{
url+='?rnd='+rnd;
}
p.open("GET",url,false);
p.send(null);
return p.responseText;
}
well, you are giving a string to document.write() function, and that's why it is displaying the string that it was supposed to display. If you want to display content of some other page you have two choices either you can use an <iframe> or use ajax.
Consider a static HTML page as test.html, and a printable version of the page has been stored in test.pdf. How can I guide browser to load and print test.pdf instead of test.html when visitors tell their browser to print?
If it's not possible how can I introduce a print button (using JavaScript) within the HTML page to do so?
You cannot force the browser to print a different file than the user is requesting/viewing. That would be a security nightmare!
Option 1 (JS (as requested) & HTML)
I suggest creating a printable version link on your site that will direct the user to the .pdf (opening the PDF in a new window would be preferable).
<!-- JS -->
<script type="text/javascript">
function LoadPrintableVersion() {
window.open("Test.pdf");
}
</script>
<!-- HTML -->
<span id="spanPrintableVersion" onclick="LoadPrintableVersion()">
Printable Version
</span>
Option 2 (pure html)
Printable Version
You can’t hijack the print command in the browser, but you can hijack keyboard shortcuts (although I wouldn’t recommend it) so that when the user prints using ctrl/cmd + p, it redirects to a PDF (or does something else). This is a usability minefield though, you should probably just create a big link that says "Printable version" and link it to the PDF (or a version of the page that uses a print-friendly CSS).
Another good options is to simply define some rules for the print media type in your CSS file, then the browsers will apply those when the user prints, without any hacks or javascript at all.
But since you asked I created a small shortcut hijacking script for the print command. It‘s kind of tricky because of the mac command key, but something like:
var cmd = false;
$(document).on('keydown', function(e) {
if(detectMacCommand(e.which)) {
cmd = true;
return;
}
// now detect print (ctr/cmd + p)
if ( e.which == 80 && ( e.ctrl || cmd ) ) {
e.preventDefault();
alert('redirect to PDF');
}
}).on('keyup', function(e) {
if(detectMacCommand(e.which)) {
cmd = false;
return;
}
});
function detectMacCommand(key) {
return ( $.browser.mozilla && key == 224 ||
$.browser.opera && key == 17 ||
$.browser.webkit && ( key == 91 || key == 93 ));
}
That’s pretty cool, but don’t use it :)
Here is the way the W3C says you should:
<LINK REL="alternate" HREF="/path/to/PDFVersion.pdf" TYPE="application/pdf" MEDIA="print" TITLE="PDF version" />
Mind you, as far as I can tell, no browser currently supports this. Sorry.