Is it possible for me to supply a client with a snippet of HTML which contains a reference to a javascript file that I host? They want to paste this HTML into their CMS, so that when their page loads, it'll load our content.
I was under the impression that there was cross domain security preventing this from being possible.
What if, instead of linking to the JavaScript, I gave them the snippet of HTML with the JavaScript already included
so instead of
<div>
<!-- link to js -->
</div>
I gave them
<div>
$.get(/*url to my content*/);
</div>
Would that work?
You could use JSONP to simulate cross domain AJAX calls (works only with GET requests as internally it uses a script tag):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data) {
$.each(data.items, function(i,item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
}
);
Is it possible for me to supply a client with a snippet of HTML which contains a reference to a javascript file that I host?
Yes. The src of script elements has no same origin limits.
$.get(/*url to my content*/);
XMLHttpRequests still do have same origin limits. XHR can only fetch from the domain of the page, not the script.
The HTML <script> tags are exempt from the same origin policy, so if your client links to your JavaScript file with <script> tags, you will not have any problems. (Source)
Referencing a javascript file from a different domain is no problem. This is not cross site scripting, it's simply a cross site HTTP request. This is used a lot, e.g. by Google's JavaScript API Loader.
Related
How can I get the html of an iframe without physically putting the iframe on the page? Can I put the iframe into a variable and get it that way?
If you're using node.js (which I would recommend for this), then take a look at jsdom.
As for javascript specifically, you cannot make a call to an external page using javascript (without using hacky methods), as it would violate Cross-domain policy
An untested afterthought, but you might be able to put an iframe hidden through css and then access the content through the document/jquery.
You can make a php-page with the HTML-content,
Easily include the file with php include:
<?php
include "filename.php";
?>
but...why?
You cannot use javascript to get content from cross domain url. So even if you have actual iframe element on your page, you will not be able to access its elements using javascript. This is called Same Origin Policy.
though JSONP is an alternative to your case, you will not be able to access elements inside iframe. You can use Jquery and JSONP to get html of cross domain page
Another option For this scenario is, you can grab the content from server side scripting language like c#, PHP
I want to load an HTML div from an html file hosted on windows azure blob (own by me) into a MVC view which is also hosted on windows azure web role ( Both the blob and the web role are owned by me ).
I tried using jquery.load() but it runs into cross domain issues and window azure blobs do not allow changing the CORS policy. Next i am trying to use Require.Js and Text.Js to achieve this cross domain load.
From the Text.Js documentation :
Text plugin determines that the request for the resource is on another domain, it will try to access a ".js" version of the resource by using a script tag. Script tag GET requests are allowed across domains. The .js version of the resource should just be a script with a define() call in it that returns a string for the module value.
My js code for cross domain call with require.js is :
require(["text!http://xxxxx.blob.core.windows.net/xxx/File"],
function (html) {
alert(html);
}
);
Now the issue which i am facing is that the File's .js version was successfully loaded by the plugin (Confirmed by using chrome inspector) but in the callback when i tried to access the text content of the file , it show me undefined. What i am doing wrong here, why the callback does not have the text content? Can anybody help me to solve this issue ? In case this is not solvable, i am open to other ways to achieve this cross domain load.
My understanding from require.js documentation is that cross domain calls can be accomplished by call a javascript version of the resource.
Try with define:
define(["text!http://xxxxx.blob.core.windows.net/xxx/File"], function (html) {
return {
template: html;
}:
}
);
Is there a way to parse html content using javascript?
I have a requirement to display only a div from some other site into my site. Is that possible? For example consider I want to show only div#leftcolumn of w3schools.com in my site. Is this even possible?
How can I do the same using javascript or jQuery?
Thanks.
You need to have a look at Same Origin Policy:
In computing, the same origin policy
is an important security concept for a
number of browser-side programming
languages, such as JavaScript. The
policy permits scripts running on
pages originating from the same site
to access each other's methods and
properties with no specific
restrictions, but prevents access to
most methods and properties across
pages on different sites.
For you to be able to get data, it has to be:
Same protocol and host
You need to implement JSONP to workaround it.
Though on same protocol and host, jQuery has load() function which you would use like this:
$('#foo').load('somepage.html div#leftcolumn', function(){
// loaded
});
Another possible solution (untested) would be to use server-side language and you don't need jsonp. Here is an example with PHP.
1) Create a php page named ajax.php and put following code in it:
<?php
$content = file_get_contents("http://w3schools.com");
echo $content ? $content : '0';
?>
2) On some page, put this code:
$('#yourDiv').load('ajax.php div#leftcolumn', function(data){
if (data !== '0') { /* loaded */ }
});
Make sure that:
you specify correct path to ajax.php file
you have allow_url_fopen turned on from php.ini.
your replace yourDiv with id of element you want to put the received content in
You will need to grab the HTML content with an HTTPRequest, then you can scrape the contents of the HTML you wish to show in your page. You would need to know some sort of server side language for this, unfortunately Ajax/jQuery will not work for this due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
what i can think of:
<div style="hidden" id="container"></div>
and then do sth like (shortcut # https://stackoverflow.com/a/11333936/57508)
var $container = $('#container');
$container.load('someurl-on-your-domain');
var $leftcolumn = $('div#leftcolumn', $container);
$leftcolumn.appendTo($sthother);
according to a comment: yes it is true, there's a same-origin policy (http://api.jquery.com/load/):
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
So why not create a proxy which is in your domain and then use the output of the proxy?! Hey, it's long-winded - true ... but it works :)
You would need to make a webservice to pull the code in. This is because you cannot pull the data in via JavaScript due to security restrictions. This is known as same origin policy and is linked elsewhere in this page.
You could use HtmlAgilityPack to parse it on the server side if you're working with asp.net technologies.
How to use HTML Agility pack
You would then be able to call the data from jQuery using .load():
http://api.jquery.com/load/
The idea being you load it into a hidden div such as:
$("#result").load("/webservice/pulldata.ashx");
and query it like you would any normal jquery element.
If you want to bypass XSS protection you can write your own server request and get info from it.
Example (php):
getContent.php
<? $fileContent = file_get_content("http://w3schools.com");
echo $fileContent; ?>
Then you can use whatever you want to modify this content (even before echo).
sample client script:
<div id="resultHtml"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#resultHtml").load("getFilecontent.php");
});
Lets assume I have my browser load an Iframe with <iframe src="test.html">
Can I, using ajax, load the content of test.html into a div in the main html page?
This idea is my solution for that fact that I'm actually trying to overcome the limitation with making ajax submits to remote hosts. The plan is to generate the dynamic page with 0 sized iframe which makes report request to remote host. Then, after the page (& iframe content) loads I will copy the iframe content into a div using JS.
Tips are appreciated,
Thank you,
Maxim.
No, you can't.
When you load a page from a different domain into the iframe, it becomes unreachable. You can no longer access the contents of the iframe, as it comes from a different domain.
The only thing that I know of that you can reliably load from a different domain is a script, which JSONP uses.
Can I, using ajax, load the content of test.html into a div in the main html page?
Yes (since your example has a relative URI and is on the same host) …
This idea is my solution for that fact that I'm actually trying to overcome the limitation with making ajax submits to remote hosts.
… and no. You still can't read data from remote hosts.
I'm sure someone will correct me if I'm wrong, but I believe that scripting across domain boundaries is restricted. Have you tried it? Here's a function that may help out.
function insertDivFromFrame(divname, framename) {
var frame = document.getElementById(framename);
var d = frame.contentWindow || frame.contentDocument;
if (oDoc.document) {d = d.document;}
document.getElementById('yourdiv').innerHTML = d.body.innerHTML;
}
I'm not sure this code works... see http://xkr.us/articles/dom/iframe-document/ for more help on this.
... you may, however, design an AJAX request to local host and retrieve information from the remote server (as described here).
If you write a php/perl/etc. script to output the contents of a document from another domain, it'll give you access to the contents as the resulting page would be considered by javascript to belong to your domain. If you're not familiar with any server-side scripting languages, I'm sure you'd be able to find a script that'll do this for you by doing a simple google search.
Best of luck.
Previously, Google's Friend Connect required users to upload a couple of files to their websites to enable cross domain communication and Facebook Connect still requires you to upload a single file to enabled it.
Now, Friend Connect doesn't require any file upload... I was wondering how they were able to accomplish this.
Reference:
http://www.techcrunch.com/2009/10/02/easy-does-it-google-friend-connect-one-ups-facebook-connects-install-wizard/
There are multiple methods of communicating between documents on different domains, amongst these HTML5 postMessage, NIX, FIM(hash/fragment), frameElement and by using the window.name property.
These are available on different browsers and in different versions, but collectively they allow you to do reliable XDM (cross domain messaging).
One project that have done this earlier is Apache Shindig, which probably pioneered quite a few of these, and more recently, the project easyXDM has come, unifying all of these approaches with a common API, making it easy to create complex applications using XDM and RPC.
You can read in depth about the various methods of transporting the data in this article at Script Junkie.
Now, to answer your question directly, earlier on it was quite common to believe that there was only postMessage, the FIM (Fragment Identifier Messaging) available, and for the latter to work efficiently, one often had to upload a special file to your domain. As more methods have been discovered, this has by many been deprecated as a technique, and hence; no more need for the file.
Just for the record; I'm the author of both the Script Junkie article, and the easyXDM library (that is what Twitter, Disqus and quite a few more are using by the way).
<edit>It's difficult to remember/verify now, but I believe my answer here was probably incorrect. Sean Kinsey's answer above should be the definitive answer to this question. If you're reading this, please upvote his answer and ignore mine.</edit>
The Google Friend Connect widget works like most ads/gadgets do, using a copy/pasted snippet of HTML to reference a JavaScript include on the host's server which then creates an iframe containing the desired content. By opening the iframe with your site ID in the URL, Google's server is able to generate the appropriate HTML document to represent a Friend Connect gadget for your particular site/settings.
There isn't any cross-site communication happening beyond that initial step of creating an iframe with the appropriate URL target. Everything inside the gadget's dynamically generated iframe is more like the user visited a separate page on Google's server, but what would have been displayed is then embedded/isolated in a block on your page instead.
I'm not sure how it works in this particular instance but cross-domain messaging can be accomplished either by the postMessage() API or by changing the hash part of the URL and monitoring that.
The hash change method works because both the enclosing and the enclosed pages have access to the enclosed page's URL.
Of course, hopefully the postMessage() API call becomes more standard over time.
JSON allows cross-domain javascript.
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain,
or protocol.
Script and JSONP
requests are not subject to the same
origin policy restrictions.
There is no other method than using the somewindow.postMessage(); for communication between cross-domain iframes.
Before somewindow.postMessage() you had to upload file in order to ensure that you can establish communication between iframes.
example:
<html>
<!-- this is main domain www.example.com -->
<head>
</head>
<body>
<iframe src="http://www.exampleotherdomain.com/">
<script>
function sendMsg(a) {
var f = document.createElement('iframe'),
k = document.getElementById('ifr');
f.setAttribute('src', 'http://www.example.com/xdreciver.html#myValueisSent');
k.appendChild(f);
k.removeChild(f);
}
</script>
<div id="ifr"></div>
</iframe>
</body>
</html>
now the http://www.example.com/xdreciver.html html content :
<html>
<!-- this is http://www.example.com/xdreciver.html -->
<head>
<script>
function getMsg() {
return window.location.hash;
}
</script>
</head>
<body onload="var msg = getMsg(); alert(msg);">
</body>
</html>
As for using the .postMessage(); its enough to use top.postMessage('my message to other domain document, which is also the main document', 'http://www.theotherdomain.com');