My Web page uses iframes to collect content from other pages. All pages are in the same domain.
From the main page, is there a way to confirm that all iframes have loaded, and that there is no 404 error?
The status only lives in the response header.
The 404 Page is handling an HTTP Status Code, which is only included in the server's response sent to the browser, but not in the actual window and document objects of the DOM that javascript may access. This means that while you certainly can collect the status-code and take appropriate actions, you may only do so when your javascript is receiving the response, such as with a jQuery.ajax() request or an XmlHttRequest to load your "iframe".
Hope the 404 page follows 404 standards.
If the above isn't an option, the only other possibility may be to check the title, and/or H tags, for " 404 ". While this is most certainly less than ideal (I'd love to see, "404, Movie not Found, the Movie."), it is your only other option.
$('#iframe').load(function (e) {
var iframe = $("#iframe")[0];
if ( iframe.innerHTML() ) {
// get and check the Title (and H tags if you want)
var ifTitle = iframe.contentDocument.title;
if ( ifTitle.indexOf("404")>=0 ) {
// we have a winner! probably a 404 page!
}
} else {
// didn't load
}
});
Suppose this is your html
<html>
<head></head>
<body>
<iframe id="iframe"></iframe>
</body>
</html>
There are two scenario
Your iframe's src is in the same domain from where your page is originated.
Ex : page url www.example.com and iframe's src www.example.com/iframe
You can use jQuery ajax request to check if the the resource is available
$(function() {
$.ajax({
type : "HEAD",
async : true,
url : "www.example.com/iframe"
})
.success(function() {
$("#iframe").attr("src", "www.example.com/iframe");
})
.error(function(){
// Handle error perhaps a failover url
})
});
Your iframe's src is not pointing to the same domain from where your page was originated.
Ex : Page url www.example.com and iframe's src www.otherdomain.com/iframe
Now browsers will not let you make a cross site request from javascript code due to cross origin policy. The way around is to make a jsonp request.
$(function() {
$.ajax({
url: "www.otherdomain.com/iframe",
dataType: "jsonp",
timeout: 5000,
success: function () {
$("#iframe").attr("src", "www.otherdomain.com/iframe");
},
error: function (parsedjson) {
if(parsedjson.status == "200") {
$("#iframe").attr("src", "www.otherdomain.com/iframe");
} else {
// Handle error
}
}
});
});
Related
I am working on an ajax function that loads another page as a way to get around iframe limitations on Shopify. My issue seems to be that the URL is blocked or headers stripped. Nothing too complex, everything worked as I needed it to by using the following:
function get_report() {
var params = {
type: "GET",
url: "https://example.com/mypage.php",
dataType: 'html',
success:function(html) {
$("#content_div").load("https://example.com/mypage.php");
},
error: function(XMLHttpRequest, textStatus) {
alert('Error : ' +XMLHttpRequest.response);
}
};
jQuery.ajax(params);
};
<button onclick="get_report()">Get</button>
<div id="content_div"></div>
This works through public networks with no problem. However, when my client uses it behind a company firewall it fails to load the page. Upon further inspection it appears that the site URL my php is hosted on cannot be loaded either (I cannot be there to physically confirm). Here is a sample of that page if its relevant:
<?php
$allowedOrigins = [
"https://myexample.com",
"https://myexample2.com"
];
if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$origin = $_SERVER['HTTP_ORIGIN'];
} else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
$origin = $_SERVER['HTTP_REFERER'];
} else {
$origin = $_SERVER['REMOTE_ADDR'];
}
if (in_array($origin, $allowedOrigins)) {
header("Access-Control-Allow-Origin: " .$origin);
}
setcookie('cross-site-cookie', 'name', ['samesite' => 'None', 'secure' => true]);
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TEST ALT IFRAME</title>
</head>
<body>
<div><?php echo "IT WORKS"; ?></div>
</body>
</html>
What I know:
-Walked client through accessing chrome console, zero errors listed
-URL never loads when client tries to load it via browser
-Ajax never gives an error response
-Webmaster/IT team is unreachable (I have tried to contact them for at least 4 months)
What I've tried:
-Recently adding meta tags and !DOCTYPE (just in case)
-Validating both the iframe site and URL site with W3C
-Confirming both the iframe site and URL site work with VPN and public networks
-Checking for correct categorization on major network filtering groups (semantics, paleo-alto, etc) and set to 'SAFE'.
My Question:
-How do I find out if the URL is blocked or the ajax request is being stripped?
-If the network is filtering my ajax URL am I at a dead end or is there another option?
How do I find out if the URL is blocked or the ajax request is being stripped?
If there's a network error, you can respond to it in the error callback you pass to the AJAX call:
function get_report() {
var params = {
type: "GET",
url: "https://example.com/mypage.php",
dataType: 'html',
success:function(html) {
$("#content_div").load("https://example.com/mypage.php");
},
error: function(XMLHttpRequest, textStatus) {
// inspect XMLHttpRequest to determine if network error occurred
alert('Error : ' +XMLHttpRequest.response);
}
};
jQuery.ajax(params);
};
If the network is filtering my ajax URL am I at a dead end or is there another option?
You're sort of at a dead end at the application level, unless you're willing to do something really convoluted like have a third party service, that you know will not have firewall restrictions, request the page, and then forward it to a service that is accessible from behind that firewall. So the short answer is, no, not really (at least not practically)
My objective is to check whether a URL is valid or not from client side. I tried the following things:
1. Tried using a ajax request using dataType as JSON. - Got the Cross-Origin Request Blocked error.
2. Tried using the JSONP as datatype. - Worked fine for some websites like google.com but it cribed for others like facebook.com
Got the error like "Refused to execute script from
FaceBook
callback=jQuery32107833494968122849_1505110738710&_=1505110738711'
because its MIME type
('text/html') is not executable, and strict MIME type checking is enabled."
Is there any workaround for this. I just want to make sure that the URL is valid irrespective of the content in the response.
Following is the code I wrote:
<html>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function CallPageMethod() {
$.ajax({
type: "GET",
url: "https://www.google.com/",
dataType: "jsonp",
success: function (data, textStatus, xhr) {
alert("Success");
},
error: function (data, textStatus, xhr) {
if (data.status === 200) {
alert("Finally I am done")
} else {
alert("Error");
}
},
});
}
</script>
<Button onclick="CallPageMethod()">Test URL</Button>
</body>
</html>
Any Suggestions or any alternative approach that I should follow to resolve this issue?
Not properly, but Most sites have a favicon.ico either from the site directly or provided from the hosting company for the site if it is a 404 image.
<img src="https://www.google.com/favicon.ico"
onload="alert('icon loaded')">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
onload="alert('ajax loaded')"></script>
Although iframe and object do have onload events, invalid pages also trigger the event.
This would be the fastest site test I can think of ...
var img = new Image();
img.onload = function () {
alert("image width is " + img.naturalWidth + " not zero so site is valid");
}
img.src = "https://www.google.com/favicon.ico";
As for facebook, the each page uses resources from another url, iframes are blocked as well as scripts. You would need to make the request from a server to test if a page existed.
You're best off writing a proxy on your server so:
Client hits your server with the URL you want to check
Your server makes the request to that URL and gets a response (or not)
Server returns status code to the client
This way will avoid the CORS issues you're having to navigate and will allow you to set any HTTP headers you need to.
I am trying to get xml through ajax like below in my javascript code
$(document).ready(function(){
$.ajax({
url: 'https://santander.easycruit.com/intranet/intranett/export/xml/vacancy/list.xml',
cache: false,
dataType: 'xml',
crossDomain: true,
success: function (xml) {
debugger;
$(xml).find('Vacancy').each(function () {
$(this).find("Location").each(function () {
var name = $(this).text();
alert(name);
});
});
},
statusCode: {
404: function () {
debugger;
alert('Failed');
}
}
});
});
but when i run code i get error XMLHttpRequest cannot load https://santander.easycruit.com/intranet/intranett/export/xml/vacancy/list.xml?_=1460979186038. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mymachinename' is therefore not allowed access
You can see there is some number appended to url like _=1460979186038
Is it because of this i am getting error.
The _=1460979186038 part is added by jquery ajax, as the mechanism to prevent cache. If I remember currectly that number is just a random + timestamp or something like that.
source: http://api.jquery.com/jquery.ajax/
The reason you are getting the error is No 'Access-Control-Allow-Origin' header is present on the requested resource, which means you are trying to send cross-domain messages but the server didn't allow it.
It's clearly that you are facing with the issue with cross domain request.
If you can control this server, you will need add the header in your server to allow cross domain or for testing purpose, you can use my add on in firefox to development and deal with CORS: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors/?src=ss
Based on comments discussion I think you should make something like proxy server. Try this PHP code:
<?php
header("Content-type: text/xml");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://santander.easycruit.com/intranet/intranett/export/xml/vacancy/list.xml");
$output = curl_exec($ch);
It would simply fetch desired XML from passed URL and display it on the page.
Put the script on the same server your javascript is and call your server with ajax. This should eliminate CORS limitations.
I am trying to create a user login/signup on my remote app that accesses user data on Salesforce. I am doing this from javascript via Salesforce REST API. This was not working using requests straight from javascript due to CORS restrictions, so I found this example. My code is as follows:
var result = sforce.connection.login('example#provider.com', 'pass'+'securityToken');
sforce.connection.init(result.sessionId, 'https://login.salesforce.com/services/oauth2/token')
sforce.connection.remoteFunction({
url: 'https://login.salesforce.com/services/oauth2/token',
requestHeaders: {
"Authorization" : "Bearer " +__sfdcSessionId,
"Content-Type":"application/json",
"Connection":"Keep-Alive"
},
method: "GET",
onSuccess : function(response) {
console.log("Success " + response)
},
onFailure: function(response) {
console.log("Failed " + response)
}
});
When I run this code I get the following errors:
1) Refused to set unsafe header "User-Agent"
2) POST http:///services/Soap/u/31.0 404 (Not Found)
3) Remote invocation failed, due to:
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /services/Soap/u/31.0 was not found on this server.</p>
</body></html>
status code:
Using a code editor I can see that the errors are occurring after hitting the sforce.connection.login() script and never making it to the sforce.connection.init() script in my code.
How do I resolve this issue so that I may log a user in from my remote web app and gain access to the user information within salesforce?
It seem your issue is like the one in this post
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
I had read earlier that cross domain requests are not possible through AJAX (since XHR is bound to same origin policy)... Hence we use JSONP, which uses dynamic script injection (since script tag is not bound by same origin policy).
However, I was going through the jQuery AJAX documentation and saw one setting saying "crossDomain".
So, is Cross domain requests now supported through jQuery/AJAX? Is it the same as what we get through JSONP?
I made a project that use cross domain requests. You have few examples.
It is here, on Github.
Use this function in your client-side code (javascript):
function getHTML(url, callback){
url = url.trim();
$.ajax({
url: url,
type: 'GET',
success: function(res) {
var headline = res.responseText;
if(headline === ""){
callback("There was a problem with the page. Be sure that your url is correct.");
return;
}
callback(null, headline);
}
});
}