Check if user can access an external resource cross-domain
I need to check if a newly registered domain has fully registered/propagated from the users browser, so I can assure they have access to it.
I have full control over the site and need to check if something as simple as a text file exists on the target domain, and if it does we are good to go. I can edit both the requesting page and the target resource. I'm 开发者_如何学Cguessing this will have to be a jQuery ajax check of some sort.
I am unable to do this in PHP because although my servers DNS has propgated, the end users' may not have.
You cant use AJAX Calls for that because it will get blocked by the same origin policy.
But you can use iframes instead:
<iframe id="check_1" src="http://www.wikipedia.com"></iframe>
<iframe id="check_2" src="http://www.aasdjflajsdflasdf.com"></iframe>
<script type="text/javascript">
$(document).ready(function() {
$('iframe#check_1').load(function()
{
alert("check 1 succeeded!");
});
$('iframe#check_2').load(function()
{
alert("check 2 succeeded!");
});
});
</script>
Assuming you don't mind throwing jQuery on your website, something like this should work as a framework:
$.ajax('http://www.example.com/text.txt', {
success: function(result) {
alert('User has access');
},
error: function() {
alert('User does not have status');
}
});
Instead of rather those useless alerts
, you could do this:
success: function() {
$.get('http://1.1.1.1/user-has-access.php?access=true');
},
error: function() {
$.get('http://1.1.1.1/user-has-access.php?access=false');
}
Went through a lot of heartache with this one and the same origin policy. In the end the most reliable/compatible way was to load an <img>
tag with an image on the target server and check for the .load
and .error
handlers in jQuery. The gotcha was that you need to set the src of the img AFTER binding the error handler.
<img id="check" width="1" height="1" />
<script type="text/javascript">
$(function() {
$("#check").error(function(){
// It failed
}).attr('src', 'http://domain.com/px.gif');
$('#check').load(function() {
// It worked
});
});
</script>
精彩评论