I am trying to understand the same origin policy of browsers. Theoretically things seem ok. So i am now trying to practically understand it using a small demo.
I have 2 domains hosted on wamp, viz domain1.com and domain2.com
domain1.com consists of index.php, innocent.php and 2 js files in a javascript folder, namely dom1_javascript.js and dom1_normal.js
here are the details of the above files: -
index.php
<?php
$value = "domain 1 cookie";
// send a simple cookie
setcookie("Dom1Cookie",$value);
?>
<html>
<script type="text/javascript" src="../javascript/dom1_javascript.js">
</script>
<body>
this is from doamin 1
</body>
</html>
innocent.php
<?php
$userSecret=$_GET['userCreds'];
if($userSecret)
{
echo "the user's secret is "+$userSecret;
}
else
{
echo "sorry user secret not found";
}
?>
dom1_javascript.js
alert(document.cookie);
dom1_normal.js
alert("alert domain 1");
alert(document.cookie);
//referring the div
var bdy=null;
// creating the form
var secretForm=document.createElement("form");
secretForm.id="goodForm";
secretForm.method="get";
var myQryStr="http://domain1.com/innocent.php?userCreds=abcd";
alert(myQryStr);
secretForm.action=myQryStr;
//creating the text box in the form
var hiddenBox=document.createElement("input");
hiddenBox.type="text";
hiddenBox.name="secBox";
hiddenBox.value="abhinav";
//appending the box to the form
secretForm.appendChild(hiddenBox);
//appending the form to the div
bdy=document.getElementById("mydiv");
alert(bdy);
bdy.appendChild(secretForm);
//submitting the form
document.getElementById("goodForm").submit();
domain2.com consists of 2 versions of index.php, viz, index.php and index1.php
here are the details of the above php file: -
index.php
<?php
$value = "domain 2 cookie";
// send a simple cookie
setcookie("Dom2Cookie",$value);
?>
<html>
<head>
<script type="text/javascript" src="http://domain1.com/javascript/dom1_javascript.js">
</script>
</head>
<body>
<div id="mydiv">
<img src="http://domain1.com/images/dom1.bmp"/>
this is from doamin 2
</div>
</body>
</html>
index1.php
<?php
$value = "domain 2 cookie";
// send a simple cookie
setcookie("Dom2Cookie",$value);
?>
<html>
<head>
<script type="text/javascript" src="http://domain1.com/javascript/dom1_normal.js">
</script>
</head>
<body>
<div id="mydiv">
<img src="http://domain1.com/images/dom1.bmp"/>
this is from doamin 2
</div>
</body>
</html>
I am using firefox as the browser to test these scritps.
First I goto domain1.com in the browser. This sets the domain1 cookie. Then I goto domain2.com/index.php
As expected, the script on domain2/index.php sets the domain2 cookie. Then the javascript from domain1 gets loaded which says
alert(document.cookie)
The execution of this script alerts the domain2 cookie value.
Assumption1: -
So my understanding here is that due to the same origin policy of the browser, even though the script was called from domain1, it did not alert the domain1 cookie, but instead alerted the domain2 cookie.
Please let me know if I am correct in the above assumption ?
Now I clear the browser cache and remove all the cookies from the browser. Run domain1.com again, which again sets domain1 cookie. And then, this time I goto domain2.com/index1.php which sets the cookie for domain2 and then accesses the script present in
domain1.com/javascript/dom1_normal.js
Now if my assumption1 was correct,( i.e. a javascript from domain1.com when imported in domain2.com will get executed with reference to domain2 only, and not its incoming domain, as per the same origin policy) then in this case also it should be the same with dom1_normal.js. So the javascript in dom1_normal.js should have access to all the HTML elements in domain2/index1.php It does not really so happen as confirmed by
bdy=document.getElementById("mydiv");
alert(bdy);
in domain1.com/javascript/dom1_normal.js which alerts null
please let me know where am i going wrong. And i have gone through more than a dozen discussions (on stack overflow and elsewhere including MDN, wiki, google etc.) and articles about same origin policy, but none of it has made the idea clear to me.
The Same-Origin policy doesn't have much to do with loading JavaScript. Regardless of where a script comes from, its actions take place under the aegis domain of the main page. Thus, if your main page comes from "domain1", then all scripts execute in the context of "domain1", whether they came from that domain or any other domain.
Note that it's not possible to access the source code of a script that loads from some other domain.
The reason your "dom1_normal" script reports "null" for that element reference is probably because you're importing the script before the <body>. The DOM is built incrementally, but scripts run synchronously when they're loaded, so if you call getElementById() for some element that's after the <script> tag, it won't be there.
Related
I have a page called main.jsp which is in domain domain1 and it has a iframe which loads contents from domain2. Basically main.jsp is a common contents and in iframe we load contents from other web applications deployed on different servers.
My problem is I want to refresh the content inside iframe automatically (say 5 seconds). I tried this code first:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />" />
Err: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame
I tried this code:
<script type="text/javascript">
window.setTimeout(function(){ window.location.reload() }, 15000);
</script>
Which also gives me same error. Can anyone guide me how to achieve this?
Note:
I have added this code to get rid of cross-domain issue:
<script type="text/javascript">
document.domain = window.location.hostname.replace('www.', '');
</script>
Try adding it dynamicaly
function addRefresh(){
var meta = document.createElement('meta');
meta.setAttribute("http-equiv", "refresh");
meta.setAttribute("content", "5");
document.getElementsByTagName('head')[0].appendChild(meta);
}
if(location.origin === 'domain1.com'){
addRefresh();
}
I want to use Jquery or javascript to get the raw content (mean everycharacter) of an Iframe. It sounds simple but I'm still struggling with finding the right way for it.
For now it is only a XML content in the Iframe though.
Here the code:
$(function() {
var xmlContent = $("#CFrame").contents().find("*").text();
// The magic
$('#SResult').xslt({xml: xmlContent, xslUrl: 'stylesheet/designSS.xsl'});
});
The html page
<form id="searchForm" method="GET" target="ContentFrame" action="http://125.235.8.210:380/search" onSubmit="processContent()">
.....
</form>
</div>
<div id="SResult">
</div>
<iframe id="CFrame" name="ContentFrame" frameborder="1" height="2000px" width="1000px" scrolling="no" src="stylesheet/test.xml"></iframe>
</body>
Thanks,
Disclaimer: I'll answer your question regardless of whether it is actually an elegant solution to your problem. Joseph seems to take that as the question. I would say he is probably right to do so.
It won't work trying to get the frame using mimetype text/xml. The browser will proceed and 'translate' the XML into HTML. That's why it doesn't sound so simple. This way it is actually impossible.
I present you with a simple work-around for this problem.
<html>
<head>
<script>
function getXmlContents() {
/*
Note: Because of security reasons, the contents of a document can be accessed from another document only if the two documents are located in the same domain.
http://www.w3schools.com/jsref/prop_frame_contentdocument.asp
*/
var iframeDocument = document.getElementById('greetingFrame').contentDocument;
if (iframeDocument == null)
return undefined;
var xmlContainer = iframeDocument.getElementById('xmlContainer');
if (xmlContainer == null)
return undefined;
return xmlContainer.innerText == null ? xmlContainer.textContent : xmlContainer.innerText;
};
</script>
</head>
<body>
<iframe id="greetingFrame" src="helloworld.html" onload="alert(getXmlContents())">
</iframe>
</body>
</html>
The contents of the XML are wrapped inside an HTML (helloworld.html):
<html>
<body>
<script id="xmlContainer" type="text/xml">
<?xml version="1.0" encoding="UTF-8"?>
<title>
Hello world
</title>
</script>
</body>
</html>
I've successfully tested this in Chrome, Firefox and IE.
Of course you would have to wrap your XML documents inside a HTML script tag as indicated above. The XML can also be wrapped in a different tag, if you'd like it rendered for example, but you'd have to encode the XML using html encoding. This needs to be done on the server-side. A very simple (php/ruby/python/etc) script would suffice.
If your XML resides on your domain, you are better off with AJAX, especially using the jQuery library, which parses it for you and make it ready for immediate manipulations.
If it does not live on your domain, then you can't access it via AJAX unless the remote server and your client's browser both support CORS.
You have options though:
If the remote server's API supports JSONP, use it instead of XML. Then you can use jQuery to retrieve JSONP data or roll your own script loader.
Or use your server to proxy the XML for you. Servers are not restricted to the Same Origin Policy. Create an API on your server that relays your form data to the remote server and retrieve the remote page - all as if your server was the browser. Then forward the results back to you.
I am having trouble displaying some jason from a page.
The data is there but I think it might have to do with this line:
document.write(fbResults.cats[0].title);
Here is the full html source:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://mydomain.com/api/get_cats', function(fbResults) {
document.write(fbResults.cats[0].title);
});
});
</script>
</head>
<body>
</body>
</html>
And here is the data that it's reading:
{"cats":[
{"id":"1","title":"mytitle1","colour":"#EE297C"},
{"id":"2","title":"mytitle2","colour":"#EE412F"},
{"id":"3","title":"mytitle3","colour":"#F5821F"},
{"id":"4","title":"mytitle4","colour":"#00AEEF"},
{"id":"5","title":"mytitle5","colour":"#00B495"},
{"id":"6","title":"mytitle6","colour":"#006476"}
]}
It is not displaying anything on the page.
On firebug console I get this error:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
No traces of the json data there
What I'm I doing whong?
You shouldn't document.write after the page has loaded (which is certainly the case here).
If you want to write it to the page, you'll need to create HTML and append it. Just replace the document.write:
$('body').append('<p>'+fbResults.cats[0].title+'</p>');
Update:
Your example makes a fully qualified URL call. Is that server the exact same one that you're running the page from? If it isn't the XHR will just eat the request (and sometime not tell you). If you need to go cross domain, you'll need to use JSONp. If you're attempting to run this locally while pulling data from the net, it'll break.
Try this
$.each(fbResults.cats,function(index,item){
document.write(item.title);
});
Working sample : http://jsfiddle.net/zWhEE/8/
its seems work for me please check this
http://jsfiddle.net/TxTCs/1/
I wanna use Facebook's Like button on my web site.
It's so simple as everyone knows but I have a problem with the censorship in our country.
Facebook is censored in our country and if I use the simple iframe, the people who have no access to Facebook (can't pass the censorship) will see the block page which I don't want to.
So I wanna check if loaded address is Facebook show them the iframe else (they will be redirected to another web site) hide the iframe.
Is there any way for me to find this out? I mean anything like address or content or id etc.
Here is my code:
<html>
<head>
<title>facebook test</title>
<style>
.facebook{
display:none;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
</head>
<script type="text/javascript">
$.ajax({
url: 'https://graph.facebook.com/btaylor?callback=?',
dataType: 'json',
success: function(data) {
$(".faceboock").show();
// alert('success - facebook works');
// alert('data = ' + JSON.stringify(data));
},
error: function() {
alert('error - facebook fails');
}
});
</script>
<div class="faceboock">
<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2Fmypage%2F152215541478267&width=292&colorscheme=light&show_faces=true&stream=true&header=true&height=427" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:427px;" allowTransparency="true"></iframe>
</div>
It works when client has access to facebook, I mean the "success: function" works but error function doesn't.
The problem is when facebook is not accessible that json never responds.
Is there any way to set a timeout for response or anything else in order to handle the error?
You can't check the content of an iframe that is not on the same domain as your code.
See Same Origin Policy
iframe.src can be checked without restrictions, but does not change when the redirect happens
iframe.contentWindow.location.href does change when the redirect happens, but can't be accessed in your case due to the security restrictions mentioned above
The only way I can think of to test this is:
Do a JSONP call to one of the Facebook APIs (JSONP has no domain restrictions)
Check the response
If these JSONP calls get redirected as well than it will most likely throw an exception instead of returning the expected values (due to the fact that it will try to parse as javascript a response which is most likely a fullhtml page)
Here is a working example using jQuery to do the JSONP call.
It works from my location, could you test it and see if you get the error alert?
You can also go in your browser to the url in the example. If facebook.com gets redirected, but this one doesn't than you'll have to find some other way to check it...
I have the following code to check whether the client has javascript enabled in their browser:
page.php:
<?php
session_start();
if(isset($_SESSION['gocheck'])) {$gocheck = $_SESSION['gocheck'];}
else {$gocheck = 'no';}
//echo $gocheck;
if($gocheck=='no'){header ("Location: ./gocheck.php"); exit;}
//Only reaches this line if gocheck.php has been run and Javascript is enabled.
unset($_SESSION['gocheck']);
//rest of page
?>
gocheck.php:
<?php
session_start();
$_SESSION['gocheck'] = 'yes';
echo"
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
<head>
<script type=\"text/javascript\" language=\"JavaScript\">
window.location.replace('page.php');
</script>
</head>
<body>
This website requires Javascript to be enabled in your browser. <br />
Please enable Javascript and try again.
</body>
</html>
";
?>
So what should happen is the user is always redirected from page.php to gocheck.php, which sets the session variable $gocheck to 'yes' and directs back to page.php via Javascript. Because $gocheck is then equal to 'yes', page.php shouldn't direct back again tio gocheck.php.
This worked fine on my PC (using WAMP), but when I upload the files to the webhost, it seems to get stuck in an infinite redirect loop between page.php and gocheck.php. Also, if I echo $gocheck in page.php, it returns 'no', so it seems as if for some reason the session variable $gocheck is not being set properly by gocheck.php.
Could somebody please shed some light on this? Is there an error in my code? Is there something I need to change in php.ini on the webhost's server?
Thanks!
P.S. WAMP on my PC uses PHP v.5.3.0, but the webhost uses PHP v.5.2.12 - don't think this can be the problem though.
Why using php to detect if javascript is enabled or not? You can just add following html tags to your page:
<noscript>
Pleas enable javascript!
</noscript>
If the user then enables javascript and refreshes the page the javascript code will work.
ok never mind, now all session variables are being set properly, maybe it was just a question of waiting a bit until the webhost configured everything correctly (also had this problem with setting up e-mails)