How to download THIS file with javascript? - javascript

The javascript inside my page needs to download the small text file (just a small JSON Array) that resides in the following location:
http://dadosabertos.rio.rj.gov.br/apiTransporte/apresentacao/rest/index.cfm/obterPosicoesDaLinha/410
The MIME type of the document is application/json.
I tried with a XMLHttpRequest but I got an error:
XMLHttpRequest cannot load http://dados[...]/410. No 'Access-Control-Allow-Origin' header
is present on the requested resource. Origin 'null' is therefore not allowed access.
I googled this, and the solutions pointed to CORS and to change things on the server side, something I cannot do.
Is there any way to retrieve this content with javascript (and only javascript)?
Thanks!
L.
EDIT
Following #naresh advice, I am trying with JSONP. I added these lines to my page, but nothing happens (not even a console error):
var source = "http://dados[...]/409";
script = document.createElement('script');
script.type = 'text/javascript';
script.src = source + '?callback=downloadLinha';
document.body.appendChild(script);
My function downloadLinha(data) is just alert(data).
EDIT 2
I contacted the server administrator, and, to my surprise, they fixed the problem in a couple of hours! I didn't expect they would even answer. So my actual problem is solved, but I could not find an answer without the administrator intervention.
Anyway, thanks A LOT to all that tried to help!

Similar to what #RobertHarvey said, the lack of a header doesn't let you access it... Via Chrome, that is. You might still be able to access it using this handy tool called anyorigin.
Check it out: http://anyorigin.com/

Nope, no can do! If I could, I would hava javascript silently load the contents of www.yourbank.com via AJAX and read whatever it can. Don't you think this is a dangerous feature with the prevalence of auto-login on the web?
You can use a proxy server, which will work as long as the target file does not depend on user-specific cookies, headers, etc.

Related

403 error when accessing an external image URL on an internal website

I've been working on this internal web app that allows the users to click on a button to see an image. Pretty straight forward.
<img id="swatchimage" width="600" height="600" src="" />
The image needs to be linked from an external website. The piece of javascript that does that is:
$("#swatchimage").attr("src", fileURL);
One of the URLs look like this:
If you try to access the image above in a browser it works without a problem.
When accessing it from the internal app ( IP: 192.168.110.15 ) then the server returns 403 error.
The same files are used in the main website, so I don't think it's about the hot linking protection (which i tried to disable too, to no avail).
Is there some restriction that I'm not aware of when linking these kind of resources?
I think I found the problem:
The server (cdn.palmcentre.co.uk) is not sending an Access-Control-Allow-Origin header in the response, so you can't use JavaScript to fetch it.
However, this is not a 403. Here's a screenshot of the error I get:
Also, what you're trying to do is not to fetch the image, but modify the src attribute of an <image> element, which should be allowed.
This makes me think that the error you're getting is because jQuery is trying to fetch the image, and failing, but I'm not sure.
Try doing this instead:
document.getElementById("#swatchimage").src = fileURL;
It seems I have found the solution.
It was puzzling indeed, because i knew that CORS would not be at play here. It was just another image URL that was requested from an HTML tag. So it shouldn't have behaved in such way.
Notwithstanding the help received, for which I am grateful, it seems that the issue was in fact a hot linking protection that was in place.
But it was not from the server itself or from the script but rather from the CloudFlare cache itself.

Convert tracking script to use JQuery by loading tracking URL when a JQuery event occurs

I'm using a tracking site to get some statistics. They say I should use the code:
var trackingstring = new String("<script src=\"http://trackingsite.com/track?C=12345&source=js\" type=\"text/javascript\"></script>");
document.write(trackingstring);
However I want to trigger a particular site statistic on a JQuery event rather than on page load, so I can't use document.write.
I believe there's actually no script to run at the URL, so I tried:
var thetrackingURL = "http://trackingsite.com/track?C=12345&source=js";
$.get(thetrackingURL);
However that gives me the error:
MLHttpRequest cannot load http://trackingsite.com/track?C=12345&source=js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.
How can I trigger that URL to be loaded by a JQuery event?
Try
var script = document.createElement("script");
script.src = "http://trackingsite.com/track?C=12345&source=js";
document.body.appendChild(script);
or, utilizing jquery
$.ajaxSetup({context:document.body});
$.getScript("http://trackingsite.com/track?C=12345&source=js");
Please read. https://security.stackexchange.com/questions/43639/why-is-the-access-control-allow-origin-header-necessary
Host your page on some local web-server using NGINX or anything else suitable.
I'm sure if you search even stackoverflow, you will find lot's of information regarding this topic.

jQuery.get() returns errors [duplicate]

This question already has an answer here:
Console shows error about Content Security policy and lots of failed GET requests
(1 answer)
Closed 8 years ago.
I use $.get function to get some html from exetrnal website in my chrome extension:
$.get(url, function(data) {
var someImgs= $(data).find('img[width="90"]').parent();
});
But I see such errors in my console:
chrome-extension://nqzxdldmasxchnkgibeedilpknlbndiho/files/image.png
I don't use any images in my extension, and I know this is link to image on exetrnal website.
What I tried:
wrap $.get() function into try-catch
handle error using $.ajaxError()
replace relevant links /files/image.png to full path: http://website/files/image.png using data.replace()
run example code in jsFiddle: errors are the same but despite of that code continiues running.
No ideas now. What I do wrong?
UPD: Error doesn't occur when I don't touch to data. When inside $.get I simple type console.log(data) there are no errors
UPD2: I also tried to download all the images whcih are mentioned in error messages and put them in the same path in my extension as on external website
UPD3: As it was mentioned in comments, images from remote website are reffering to relative paths. So I tried to replace relative paths in 'src' attribute to full, using this code:
var data = data.replace('/sites/default/', 'http://website/sites/default/');
As you guess - result is the same, same errors.
UPD4: Seems like replacement wasn't successful. I checked the above replacement and it says nothing changed:
console.log(data.indexOf('src="/sites/default/')); //returns integer
So, actually it was solved by downloading remote images to my extension foled. Little 'nasty' way but the only workable. Thanks to all the commentators that helped me to find out the source of problem.
Edit: On second look it appears that the html of the page at url contains images with relative file paths (like /files/menu_banners/ktc_apple.png), but when you interpret it and treat it with jQuery as a DOM object, it fails to load them because their urls are now interpreted as relative to the extension (cross-origin restrictions still apply, but that's not the issue since you've edited the manifest)
--
You are trying to make a cross-origin request, but jQuery isn't aware of a correct API to use when included in an extension and that is why it's failing. You can read more about XHR in Google Chrome extensions; you basically need to allow cross-domain access to your website URL:
By adding hosts or host match patterns (or both) to the permissions
section of the manifest file, the extension can request access to
remote servers outside of its origin:
//manifest.json
{
"name": "My extension",
...
"permissions": [
"http://www.google.com/"
],
...
}
So in your manifest you should include your http://website url, or use a wildcard http://*/ and allow access to any domain (handy in dev, terrible idea security-wise in production)

Reading code from GitHub as text (raw) in a web page

I'm trying to read some source code (C language) from my GitHub repository to be shown as text in my webpage. I can access the code in raw mode through https://raw.github.com.
I'm using jQuery GET function to read the data but it doesn't work. Problem is related with XMLHttpRequest and Access-Control-Allow-Origin but, despite I found some related question on stackoverflow (XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin) it didn't work for me. I tried everything.
My jQuery code:
<script type="text/javascript">
$(document).ready(function() {
var url = 'https://raw.github.com/raysan5/raylib/master/examples/ex01_basic_window.c';
$.get(url, function(data) {
$('#code').text(data);
}, 'text');
});
</script>
Please, could someone help me with this issue? Many thanks!
You could try and delete the dot between raw and github:
https://rawgithub.com/raysan5/raylib/master/examples/ex01_basic_window.c
See rawgithub.com, also explained in this blog post:
GitHub discourages this, since they want repo owners to use Github Pages to host specific versions of their files. They discourage it by serving files from the “raw” domain with Content-Type: text/plain instead of Content-type:application/javascript.
This wasn’t a problem until recently, when Google Chrome implemented a security fix that prevents JavaScript from being executed if it has an incorrect Content-type.
This makes sense when you’re viewing pages outside of your control. But when it’s you who’s deciding what scripts to include, it’s a hassle.
As Rob W comments below:
It's worth mentioning that the only reason that this web service solves the OP's problem is that it includes the Access-Control-Allow-Origin: * response header.

crossdomain iframe handling

Hi I have a question about iframes and crossdomains.
The answers I found left me just confused. Some say it's possible, others say it's not possible. So I hope that someone here will give me the answer I've been looking for. so my question goes like this:
for example I have the website:
www.apple.com and I load an iframe with a new url: www.banana.com. In www.banana.com I have 2 comboboxes, When I change the value of the first, the second would be changed. But when I change the value I get a permission denied.
I don't have to copy the value to www.apple.com, so it stays in www.banana.com. What did work was when I opened the frame in a new tab. So my question is: is it a cross domain issue and is there a way to let the comboboxes work?
I work with this line in www.banana.com :
if (window.parent.vulin){
var docPrefix = window.parent.vulin;
}else{
var docPrefix = window.parent;
}
and it's the parent.vulin that has the permission problem.
Since you have some amount of control over both domains, you can get around the cross-domain policy using "Cross-Origin Resource Sharing," or CORS.
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
The technique involves having the server of the target window send the Access-Control-Allow-Origin HTTP header, and modifying the JavaScript code in the other window slightly to appease IE.

Categories