How to disable Cross Domain Restriction - javascript

I am providing web service which return data as JSON object. The problem is with Ajax, Ajax can't call cross domain url. Is it possible to disable it?

You can't disable it, but you can solve the problem by accepting JSONP-requests.

Use JSONP if you can control what the other server responds.
JSONP has to return a javascript compliant script. (var hi = {json = stuff};)
Example for the client HTML:
// This is our function to be called with JSON data
function showPrice(data) {
alert("Symbol: " + data.symbol + ", Price: " + data.price);
}
var url = “ticker.js”; // URL of the external script
// this shows dynamic script insertion
var script = document.createElement('script');
script.setAttribute('src', url);
// load the script
document.getElementsByTagName('head')[0].appendChild(script);
In this case the "ticket.js" url contains something like this:
var data = {symbol: 'Hi', price: 91.42};
Possibility two is you create a local (php, perl, ruby, whatever you use) script which proxies to the external JSON source.

Related

How to look up URL names in Javascript

How can you use Javascript to parse out the URL of a page?
First of all, you have to decide whether you want to do this on the client or on the server. On the server, you can load the XML and use XPath to locate the part of the XML DOM tree that contains the site:
//site/name[text() = 'Blah00']
When using JavaScript on the client, a better solution would be to have a server which keeps the current status per site (use a database or some in-memory structure). Then use AJAX requests to ask the server for the information for a certain site. jQuery will make your life much easier.
I have solved this:
<script>
function mySiteURL() {
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
}
</script>

Change html page content

I am creating Firefox addon using the Add-on SDK. I want to get data from remote url and inject it in current html. As of now i m able to fetch data using request module of Firefox addon sdk but m not able to inject it in current page.
for example : i am fetching response from website "abc.com".after fetching response i will augment current page with response
// main.js
var widgets = require("sdk/widget");
var tabs = require("sdk/tabs");
var Request = require("sdk/request").Request;
//create addon widget
var widget = widgets.Widget({
id: "div-show",
label: "Show divs",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function() {
//initializing request module to fetch content
quijote.get();
}
});
//fetch content of requested page
var quijote = Request({
url: "http://localhost/abc/",
overrideMimeType: "text/plain; charset=latin1",
onComplete: function (response) {
//check if content is fetched successfully
addContent(response);
}
});
//try and modify current page
function addContent(response){
//initialize page modification module
var pageMod = require("sdk/page-mod");
tabs.activeTab.attach({
contentScript: 'document.body.innerHTML = ' + ' "<h1>'+response.text+'</h1>";'
});
}
Is their any way in which i can augment my current page???
Your code will bitterly fail e.g. when response.text includes a double quote.
Then your code would be (assume it is world):
document.body.innerHTML = "<h1>world</h1>";
This is obviously invalid code.
Your code basically constructs a dynamic script from unsanitized data, which is a bad idea because (other than the escaping problem above)
you'll be running an unsanitized content script if that code is even valid and
if that would succeed, the page might run unsanitized code as well.
This is the web equivalent to SQL injection attacks....
First, lets tackle 1.) with messaging (more):
var worker = tabs.activeTab.attach({
contentScript: 'self.port.on("setdom", function(data) { ' +
+ 'document.body.innerHTML = data; /* still a security issue! */'
+ '});'
});
worker.port.emit("setdom", response.text);
This guarantees that the content script will be valid (can even run) and does not run arbitrary code.
However 2.) is still a problem. Read DOM Building and HTML insertion.

Method for data transfer with bookmarklet

I'm building a bookmarklet for a service. I need to transfer data (url, text) from open window but I don't know which would be the best method. GET limits the amount of data and ajax isn't possible due cross-domain problem.
What would be the optimal way?
You could use POST if it's a lot of data. Create a hidden iframe with a form with a textbox. Set the form method to post and the action to your service. Put the data into the textbox, attach the iframe to the document, and submit the form.
Try something like this:
function postData (data, url, cb) {
var f = document.createElement('iframe'),
fname = (+((''+Math.random()).substring(2))).toString(36);
f.setAttribute('name', fname);
f.setAttribute('id', fname);
f.setAttribute('style', 'width:0;height:0;border:none;margin:none;padding:none;position:absolute;');
document.body.appendChild(f);
var frame = window.frames[fname],
doc = frame.document,
form = doc.createElement('form'),
text = doc.createElement('textarea');
text.setAttribute('name', 'data');
text.appendChild(doc.createTextNode(data));
form.setAttribute('action', url);
form.setAttribute('method', 'post');
form.appendChild(text);
doc.body.appendChild(form);
if (cb) { document.getElementById(fname).onload=cb; }
doc.forms[0].submit();
}
You can remove the iframe from the document in the callback if you want.
You can put your data in an encoded JSON string and send it with and AJAX POST. AJAX support POST.
The method no recommends would work.
An alternate method, to get around the cross-domain issue: you can host a JS file with a majority of the JavaScript required (including the XHR code), and simply use your bookmarklet code to inject a script element into the current page referencing your JS file (line-breaks added for readability; remove them in the bookmarklet code of course):
javascript:(function() {
var sc = document.createElement("SCRIPT");
sc.type = "text/javascript";
sc.src = "http://domain.com/path/to/script.js";
document.body.appendChild(sc);
})();

XMLHttpRequest not working with http

Below code is working properly now. But if I replace 'text.txt' with 'http://google.com' isn't showing anything, nor displaying an error.
What am I doing wrong?
I need this code to get content of an url to a string, on client side.
Thakns.
<script type="text/javascript">
var webUrl = 'text.txt';
var queryString = '';
var xmlText = getAjaxValues(webUrl, queryString);
window.alert(xmlText);
document.write(xmlText);
function getAjaxValues(webUrl, queryString)
{
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open("GET", webUrl, false);
xmlHttpObject.send();
var xmlText = xmlHttpObject.responseText;
return xmlText;
}
</script>
It's being prevented by the same origin policy, which requires that any AJAX requests, except for scripts and, by extension, jsonp, be made to servers in the same domain as the original page request. Your best bet is to create a proxy method on your server that can accept the url that you want to get the content of and have it request the page and pass it back to the client.

Cross-site XMLHttpRequest

I want to provide a piece of Javascript code that will work on any website where it is included, but it always needs to get more data (or even modify data) on the server where the Javascript is hosted. I know that there are security restrictions in place for obvious reasons.
Consider index.html hosted on xyz.com containing the following:
<script type="text/javascript" src="http://abc.com/some.js"></script>
Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?
Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?
No, because the script is loaded on to a seperate domain it will not have access...
If you trust the data source then maybe JSONP would be the better option. JSONP involves dynamically adding new SCRIPT elements to the page with the SRC set to another domain, with a callback set as a parameter in the query string. For example:
function getJSON(URL,success){
var ud = 'json'+(Math.random()*100).toString().replace(/\./g,'');
window[ud]= function(o){
success&&success(o);
};
document.getElementsByTagName('body')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = URL.replace('callback=?','callback='+ud);
return s;
})());
}
getJSON('http://YOUR-DOMAIN.com/script.php?dataName=john&dataAge=99&callback=?',function(data){
var success = data.flag === 'successful';
if(success) {
alert('The POST to abc.com WORKED SUCCESSFULLY');
}
});
So, you'll need to host your own script which could use PHP/CURL to post to the abc.com domain and then will output the response in JSONP format:
I'm not too great with PHP, but maybe something like this:
<?php
/* Grab the variables */
$postURL = $_GET['posturl'];
$postData['name'] = $_GET['dataName'];
$postData['age'] = $_GET['dataAge'];
/* Here, POST to abc.com */
/* MORE INFO: http://uk3.php.net/curl & http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html */
/* Fake data (just for this example:) */
$postResponse = 'blahblahblah';
$postSuccess = TRUE;
/* Once you've done that, you can output a JSONP response */
/* Remember JSON format == 'JavaScript Object Notation' - e.g. {'foo':{'bar':'foo'}} */
echo $_GET['callback'] . '({';
echo "'flag':' . $postSuccess . ',";
echo "'response':' . $postResponse . '})";
?>
So, your server, which you have control over, will act as a medium between the client and abc.com, you'll send the response back to the client in JSON format so it can be understood and used by the JavaScript...
The easiest option for you would be to proxy the call through the server loading the javascript. So some.js would make a call to the hosting server, and that server would forward the request to abc.com.
of course, if that's not an option because you don't control the hoster, there are some options, but it seems mired in cross browser difficulties:
http://ajaxian.com/archives/how-to-make-xmlhttprequest-calls-to-another-server-in-your-domain
You could use easyXSS. Its a library that enables you to pass data, and to call methods across the domain boundry. Its quite easy and you should be able to use it.
There are many examples on the code.google.com site

Categories

Resources