Can I using cross-site XmlHttpRequest in Itunes LP environment? - javascript

Itunes is based on Webkit platform and we can't use cross-site XmlHttpRequest in JavaScript because of security policy. But, as a exception, we can do that with a special header.
Here is source code and I did it successfully in Safari:
var url = 'http://mysite.net/canvas.php';
var mybody = "<?xml version='1.0' charset='utf-8'?><person><name>Arun</name></person>";
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("X-PINGOTHER", "pingpong");
http.setRequestHeader('Content-Type', 'application/xml');
http.setRequestHeader("Content-length", mybody.length);
http.setRequestHeader("Connection", "close");
http.send(mybody);
I sent xml data to my server and get return response successfully in Safari browser but i can't do it in iTunes LP environment. So what is the problems?

I don't know what iTunes LP environment is but normally, if you need to do cross site scripting you'd use JSONP. Look into that. I'm sure you can find loads of examples.

JSONP is good option, but in order to do that, you need to create the service to provide the feature of JSONP.
But, you not may the owner for that.
You can go with proxy to send the XmlHttpRequest which you can use Flash as proxy.
You can find better example here

Related

When tried to convert to base64 from url - getting CORS Issue in JS

when i tried to convert image url to base64 am getting CORS issue.
Not sure what exactly need to do to get rid of this CORS issue
my code look like this
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.dropbox.com/******/gradient-test.jpg?dl=1', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
am getting this error
Access to XMLHttpRequest at 'https://www.dropbox.com/****/gradient-test.jpg?dl=1' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.**
and am not able to console ,since CORS issue.
Can any guys help me to get rid with an jsfiddle or an live example
The CORS issue you are facing is because you are trying to access the www.dropbox.com domain from a different domain. The short answer is that you can't fix this from your own domain--it requires cooperation from the www.dropbox.com domain to fix this. You are the client in this case, and dropbox is the server, so as a client you can't tell the server what security settings to use. The server can opt in and could configure their site to allow your origin, but that isn't something dropbox is likely to do. You'll need to re-architect your approach. (also see Ways to circumvent the same-origin policy if you don't believe me when I say you need to re-architect your approach.)
Check out https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more background:
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from unless the response from other origins
includes the right CORS headers.
You could try using JavaScript to inject a script tag into your DOM that sets the type of the script tag to something other than JavaScript. Then you could have your code read the contents of that and make use of it...but that is a completely re-architected approach. See How does HTML tags work inside script tag? and https://stackoverflow.com/a/8578840/230055 if you want to look into that.

JavaScript XMLHttpRequest vs curl

using curl I can send a POST request to
"http://myusername:mypassword#SomeURL" to trigger an action
Using xml http request I've tried doing the same thing but running the following code:
xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://myusername:mypassword#SomeURL", true);
xhttp.setRequestHeader("Content-Type", "text/plain");
xhttp.send();
Greets me with the error:
POST http://myusername:mypassword#SomeURL 403 (Forbidden)
Now why would this be ? Is accessing an url like this via a browser, curl, arc... etc different from accessing it via .js ?
Furthermore I've tried posting to said url using the action of a form and it worked swimmingly, but I'd prefer to get things done in JavaScript if possible for this specific task.
So... ahm, any ideas ? The documentation behind the XMLHttpRequest that i've seen has been rather lack-luster for a technology that "carries the modern web upon its shoulders".
Necessary reading to solve this question:
Basic Authentication With XMLHTTPRequest
How can you encode a string to Base64 in JavaScript?
I am deliberately not adding a code sample; the linked questions have everything you need.
Sounds like you might need to enable CORS (cross-origin resource sharing)

Simple CORS does not work (even though it should)

I'm trying to hack my back-end, which exposes a REST API. The worst thing that can happen to my database according to firefox CORS policy is that I can create a new object with POST request, as it does not need a preflight. This is the simple code (I'm running it via jsfiddle, but it shouldn't mean a thing)
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:8000/api/v1/company", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.send('{description:"This company was added by pure hacking"}');
But I'm getting an error in the console:
Blocked loading mixed active content "http://127.0.0.1:8000/api/v1/company"
The error is not because of SOP, its a mixed content error, that is making an http request on a https page.
jsfiddle defaults to https but allows http, but only on saved fiddles.
Change the url of your fiddle to use http instead of https

Remote calls via javascript

I run a service where there is a javascript file that is called and self executed on a user's site.
This then calls an external server every 10 or so seconds with a bunch of variables.
I used to do this by using a createElement('script') and then setting the path to a file on the external server and passing the required variables across by means of GET variables. (works well for small URI's)
This worked really well and seemed to work cross browser as well with no undesired effects.
The problem I then ran into was when I needed to extend the amount or size of the variables that were being sent across. So obviously I decided to change from GET method to POST, but by doing that I could no longer use the createElement('script') trick and had to opt for the XMLHttpRequest() (ala Ajax - without jQuery) method which worked really well, except for the minor problem of having to also cater for Internet Explorer and Opera which didn't really play ball too well (big shock). So I used the following:
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("post", "http://xx.xxxx.com/");
if (request){
request.onload = function(){
//do something with request.responseText
};
request.send(myPostObjectDataVariableGoeshere);
}
..which I found over at this page
This is basically just a fallback to using the XDomainRequest() method which InternetExplorer wants you to use instead..
Fantastic, BUT -> Looking in the Console of Developer Tools in IE it says:
SEC7118: XMLHttpRequest for http://xx.xxxx.com/ required Cross Origin Resource Sharing (CORS).
SEC7120: Origin null not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
But what's really odd about this is that I've already got the following as the first line in my backend PHP file that is being called (which works for other browsers...)
header('Access-Control-Allow-Origin: *');
Someone please tell me what's wrong here.. Also if there is a better way to be doing this instead of fighting the browser wars..
Note: I cannot use jQuery for this task!
You should try jQuery for this task. Its much easier and don't have that problem with IE.
http://api.jquery.com/jQuery.ajax/
IE unfortunately block Cross Origin requests, i believe there is no simple way to get around it by script only, but you can try tuning the options or via my proxy script.
Tuning the options
Internet Explorer ignores Access-Control-Allow headers and by default prohibits cross-origin access for Internet Zone. To enable CORS go to Tools->Internet Options->Security tab, click on “Custom Level” button. Find the Miscellaneous -> Access data sources across domains setting and select “Enable” option.
Proxy Script on local server as a Bridge
Previous post:
Remote POST request with jQuery and Ajax
This is for you to place a PHP script on a local server and do a local AJAX request and proxy to the remote server for good.

Open webpage and parse it using JavaScript

I know JavaScript can open a link in a new window but is it possible to open a webpage without opening it in a window or displaying it to the user? What I want to do is parse that webpage for some text and use it as variables.
Is this possible without any help from server side languages? If so, please send me in a direction I can achieve this.
Thanks all
You can use an XMLHttpRequest object to do this. Here's a simple example
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mydomain.com/', false);
req.send(null);
if(req.status == 200)
dump(req.responseText);
Once loaded, you can perform your parsing/scraping by using javascript regular expressions on the req.responseText member.
More detail...
In practice you need to do a little more to get the XMLHttpRequest object in a cross platform manner, e.g.:
var ua = navigator.userAgent.toLowerCase();
if (!window.ActiveXObject)
req = new XMLHttpRequest();
else if (ua.indexOf('msie 5') == -1)
req = new ActiveXObject("Msxml2.XMLHTTP");
else
req = new ActiveXObject("Microsoft.XMLHTTP");
Or use a library...
Alternatively, you can save yourself all the bother and just use a library like jQuery or Prototype to take care of this for you.
Same-origin policy may bite you though...
Note that due to the same-origin policy, the page you request must be from the same domain as the page making the request. If you want to request a remote page, you will have to proxy that via a server side script.
Another possible workaround is to use Flash to make the request, which does allow cross-domain requests if the target site grants permission with a suitably configured crossdomain.xml file.
Here's a nice article on the subject of the same-origin policy:
Same-Origin Policy Part 1: Why we’re stuck with things like XSS and XSRF/CSRF
Whatever Origin is an open source library that allows you to use purely Javascript to do scraping. It also solves the "same-domain-origin" problem.
http://www.whateverorigin.org/
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){
alert(data.contents);
});
You can try using fetch and it's callback
fetch('https://api.codetabs.com/v1/proxy?quest=google.com').then((response) => response.text()).then((text) => console.log(text));
You could open the new window in an iframe:
http://www.w3schools.com/TAGS/tag_iframe.asp
Although note that Javascript access is limited if the site you open is from a different URL. This is to prevent cross-site scripting attacks:
http://en.wikipedia.org/wiki/Cross-site_scripting
You would use AJAX. This would make a Get request to the URL in question and return the response HTML. Jquery makes this very easy e.g.
$.get("test.php");
http://docs.jquery.com/Ajax
Andrew

Categories