I'm trying to make an XML request inside the content.js file of a chrome extension I am making. I'm having trouble, however, making the request, and adding the appropriate event listeners. In the current configuration, the open after the listeners, the console says my request needs to be open before being sent, although you'll note that the send method is only called in the callback function when the request has been loaded. In the case that I put the open before the event listeners, the console says that the request has been aborted. If there is a better way of requesting and parsing XML data within a google chrome extension application, I would appreciate any advice. I've left the link in so you can see what type of XML data I'm dealing with.
var l = "https://video.google.com/timedtext?lang=en&v=5MgBikgcWnY";
function addScript () {
$(document).ready(function() {
$('#related').prepend('<div id="script-box" class="col s12"></div>');
$('#script-box').append('<h3 id="script-title">Quote</h3>');
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", console.log("The download is still in progress"));
xhr.addEventListener("abort", console.log("This process has been aborted"));
xhr.addEventListener("load", parseXML(xhr));
xhr.addEventListener("error", console.log("An error has ocurred."));
xhr.open('get', l, true);
});
}
function parseXML(r) {
r.send();
var result = r.responseText;
console.log(result);
}
Related
I've been following this Google File Picker tutorial and I've gotten so far as to get the file picker showing and getting the URL, but I don't know how to download the file using JavaScript. If I can use VB.NET, then can someone point me in the right direction?
I've been able to download files with VB.NET from my own database, but I don't know how to get it with the Google API or with JavaScript.
All of the file picker code works, and I'm calling this from the onSelect of the FilePicker:
function downloadGDriveFile(file) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl); // use selfLink??
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function () {
var content = xhr.responseText;
};
xhr.onerror = function () {
alert('Download failure.');
};
xhr.send();
} else {
alert('Unable to download file.');
}
}
And when I click on the download URL I get this error:
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
The error you posted is an issue with your account reaching it's max usage limit. Different issue than downloading the file. I don't have any knowledge on the google file picker api, but I'm going to assume this is in the browser.
You may have to specify req.responseType = "arraybuffer" because it could default to json.
I recommend using http://danml.com/download.html. Browser API does not expose the download modal for security reasons. The hack is to create an invisible a tag set the url to the blob of the body that you received and programmatically click the tag. The library provided does exactly that.
I have a number of AJAX requests (made with regular JS) that seem to be causing trouble when they make requests of my Python GAE back end. Here's an example:
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.send(JSON.stringify(requestOjb));
},
I am getting a code 400 with a Parse Error, but only on my deployed server. Everything works fine on the dev server. The error says the problem is with my back-end function "new_game", but does not specify a line where the error occurred. The endpoint function works correctly when I access it directly from the API explorer, so I figure the problem must be a result of the data sent from my JS file. Here's that function anyway:
#endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='new_game',
http_method='POST')
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
# ... removed unnecessary code for this question
return game.to_form('Good luck playing Battleship!')
The request message it's expecting takes the form of {'user_name': 'some_name'} and it appears, through console.log, that JS is sending it in the right format.
The log where the parse error comes up is interesting, because it shows a 200 code POST request, although it mentions the 400 error when I dive into that log.
I've double and triple checked that my code works on the dev server, and that I've got the exact same code deployed. I don't know where to look next to continue debugging this thing. Any help is appreciated.
Figured it out. I tried running the AJAX request with jQuery, and got a slightly different error message, which lead me to find that I had to set the request header, because it was causing the server to read the incoming data differently than it should have. The following AJAX request now works perfectly.
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(requestOjb));
},
I am trying to get binary data of an image from another domain with an AJAX request. I tried various methods, but there was no working solution. I found some code on the internet that looked good, but even with this calls I get errors.
What do I wrong? Is there a standardized way to do this?
Here is what I tried until now:
var request = this.createCORSRequest('GET', 'http://url/to/image.png');
request.onload = function () {
var text = request.response;
};
request.onerror = function (error) {
alert('Woops, there was an error making the request.');
};
request.send();
private createCORSRequest(method, url) {
var xhr: XMLHttpRequest = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
var xdhr = new XDomainRequest();
xdhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
I even found this solution without ajax here on stackoverflow, but it does not work for me:
Asynchronously load images with jQuery
Here a screen of the properties the error event contains:
My goal is to get the binary of an image from a url which I get from an atom feed . I need the binaries to copy the picture to MS SharePoint.
You cannot get data from another domain unless :
the remote server allows it using CORS
you run your browser in an unsafe mode.
Reason : otherwise site A would be able to (maliciously) read the user data from site B
You must add headers to the method to allow cross domain request.
For example, if you are trying to get data from www.example.com/main.php , then you must add headers to allow those method to be called from different domain.
I'm trying to make a chrome extension that requires to do some API calls to my secure server.
I'm testing this locally first, with my own created ssl certificates.
My problem is that when i try to do an API call to my server (https://:9000/api/project) i get an error saying: net::ERR_INSECURE_RESPONSE.
The weird thing is that i can perfectly do that POST call from other REST clients with no problem, so i know the issue is in the code of the chrome extension.
The xhr request is being done in the background.js script like this:
var sendProject = function(projectData) {
var openhuntURL = 'https://<mylocal>:9000/api/project';
xhr.open('POST', openhuntURL, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(true);
}
else {
callback(false);
}
};
xhr.send(projectData);
};
I don't know what i should do to allow the extension to make that request.
By the way, just before that api call i make another api call to another website and it works just fine.
Thanks for your help!
I had the same issue, and comes to know that there is no such way you can override self signed certificate.
I'd like to know if HTML5 API may fit this use case:
some videos are present on a public server (say http://videosanbox.me/video.mpg)
the JS/html5 app should store the videos locally in order to be able to play them also off-line (videos are public, there are no security
warnings)
In my initial tests I am unable to go past the "No 'Access-Control-Allow-Origin'" error.
In my understanding the following script should:
request with a get the content located at the given URL
prepare 1Mb file somewhere (I assume I'll have other errors here, but I'll get there when I'll see them:))
for now I'm interested in understanding why this error is happening, wouldn't it be normal for a client (a mobile browser) to query for resources which are not already on it?
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://videosanbox.me/video.mpg', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
window.requestFileSystem(TEMPORARY, 1024 * 1024, function(fs) {
fs.root.getFile('video.mpg', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) { alert('writing'); };
writer.onerror = function(e) { alert('error'); };
var blob = new Blob([xhr.response], {type: 'video/mpg'});
writer.write(blob);
}, onError);
}, onError);
}, onError);
};
xhr.send();
onError is just doing something in case of error: function onError(e) {console.log('Error', e);}
Solution 1
On the server side, you need this header to be passed:
header('Access-Control-Allow-Origin: *');
Unfortunately, that may not be possible if you don't have control over videosanbox.me. If not, contact them and see if they're willing to allow this. If not, don't worry, there's a second solution:
Solution 2
Create a web page on your own server and allow cross site scripting (but use security to restrict who can use this page). In that page's code, it will take the request and open an HTTP connection to http://videosanbox.me, retrieve the mpg file and spit it back to the PhoneGap app as a Blob. Your PhoneGap would connect to this page (on your server) via Ajax instead of http://videosanbox.me.