Get JSON in a Google Chrome Extension - javascript

I would like to make a google chrome extension, however I have been rubbing my head on a problem all night. I have the following code giving me a problem:
var xhr = new XMLHttpRequest();
var resp;
xhr.open("GET", "http://www.roblox.com/catalog/json?Subcategory=16&SortType=3&ResultsPerPage=10", true);
xhr.onload = function () {
resp = JSON.parse(xhr.responseText);
}
xhr.send();
I'm attempting to obtain some JSON data. If I replace this section of code with var resp = //(The actual JSON data itself), then the extension works just fine.
How can I fetch this JSON data correctly, and still have it compactable with anyone who downloads my extension?
Sorry if there's an obvious answer, I'm still new to Javascript.
Thanks!

Try setting the content type. Not all browsers use the same default.
xhr.setRequestHeader("Content-Type", "*/*");

Related

How to fix RichAPI error in word javascript API (Trying to add an image into the document)

So im making a add in for word and ive been getting this issue:
--
Uncaught (in promise) RichApi.Error: GeneralException
at new n (word-win32-16.01.js:25:246592)
at i.processRequestExecutorResponseMessage (word-win32-16.01.js:25:310758)
at word-win32-16.01.js:25:308821
--
This is the code thats throwing the error:
function insertImage(baseUrl) {
Word.run(function (context) {
// Get the current selection
var selection = context.document.getSelection();
// Insert the image into the document
var picture = selection.insertInlinePictureFromBase64(baseUrl, Word.InsertLocation.before);
// Queue a command to load the picture
context.load(picture);
// Synchronize the document state by executing the queued commands
return context.sync().then(function () {
console.log("Image inserted successfully");
});
});
baseUrl is an base64 url that has been converted in an previous function
this function:
function toBase64URL(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.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.responseType = 'blob';
xhr.send();
}
Im kinda new to this stuff still a student
Ive tried changing my input different images it changed nothing
Ive also given it all headers methods ext.
So far nothing has worked and i cant find any solutions that work online.
EDIT
Ive done some research and tested some things as one of you reccomended but im still not making it work.
I have tho taken a picture of the error maybe this gives some more information, it also includes some extra information and the base64 string
Error from taskpane.js
The answer for anyone looking in the future is related to the comment under my post
"Perhaps this: The documentation for readAsDataUrl at developer.mozilla.org/en-US/docs/Web/API/FileReader/… says "Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:/;base64, from the result.""
I researched into this and stripping the base64 string from data:/;base64, worked
here is the function for anyone who needs it
var base64Stripped = baseUrl.split(',')1;

reading an object URL produced in a worker with IE

I have a webworker that is producing a CSV for downloading, and to conserve memory I only have it return the URL it produces from teh blob..
My worker code looks something like::
var blob = new Blob([ResultOfSomeWork()],{type:'text/csv'});
URL.createObjectURL(blob);
self.postMessage({url:blob.url});
My goal is to just be able to download it in firefox and chrome this is very easy as I can just set up an invisible <a> and have it be clicked to download it.
For IE10 I want to use msSaveBlob but I need a blob which I don't want to transfer.
How can I download a object dataurl in IE10?
So I found a solution that works. Apparently, I can XHR and read the content back in my main thread.
worker.onmessage = function(event){
var url = event.data.url;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType='blob';
xhr.onload = function(){
msSaveBlob(xhr.response, fileName +'.csv');
};
xhr.send();
}
While this feels extremely complicated it works well in practice and is really fast.

Sending tab screenshots to a remote server from a firefox addon

I have firefox addon (made using the firefox addon sdk) which when instructed takes a screenshot of the currently active tab and sends it in an ajax request to a remote server.
The following code in addon-script main.js is responsible for taking getting the thumbnail
var tab_image_data=tabs.activeTab.getThumbnail();
var tab_image_data = base64.encode(tab_image_data);
panel.port.emit("screenshot",{image_data:tab_image_data});
The image data generated by the function getThumbnail() is sent to a content script file belonging to a panel.
In the content script the following code is responsible for sending the image data to the server
var tab_image_data=addonmessage.image_data;
var myBlob = new Blob([tab_image_data], { "type" : "text/base64data"} );
var formData = new FormData();
formData.append('img',myBlob);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xyz.abc.com/imageshot/index.php", true);
xhr.onload = function() {
if (xhr.status == 200) {
console.log('all done: sq');
} else {
console.log('Nope');
}
};
xhr.send(formData);
Everything works fine and the image file is created on server in jpeg format. But when I try to view that image, the windows photo viewer gives a not supported file format error.
I tried to base64 encode the data before sending it but that did not work as well. Suprisingly I have a chrome extension that performs a similar function and that works flawlessly. In both cases the same php script is being used on the server side.
Any help regarding this matter will be highly appreciated
Thanks in advance.

'Access is denied' exception trying to download binary file stream

I am receiving an XmlHttpRequest's response in my code, which is a binary stream of a file. The response has the correct size and mimetype. I would like to download this file to disk, by issuing the typical browser prompt for saving files. I have the following script in place which works perfectly fine in Chrome. It fails for IE though.
var url = /my_rest_url/;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function (e) {
if (xhr.readyState == xhr.DONE) {
var blob = xhr.response;
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
}
xhr.send();
The failure happens on the window.open() call, where IE fails with an exception that says "access is denied". I have researched for hours on end without finding a solution which works for me. I have seen some recommendations to use a 'hidden iframe' to start the download, but it hasn't worked out for me. Has anyone ever made something like this work in IE? Would be glad to get some ideas.
ps/ I know blob and createObjectURL are relatively new. And even though they are supported by IE10 and above, I would really feel better to get rid of these and achieve this an 'old-school' way, if there is any.

Chrome Application JSON data open file

I want to create a Chrome Application. If I put a JSON file in the same folder how do I access the file? I want to find the correct way of getting the text into a variable, something like the example I found:
var json = $.getJSON("data.json");
I could not find in this example where the $ object is defined. It must be some class. How can I use this in a Chrome Application?
I found out that it works the exact same way as if it was cross-origin:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(JSON.parse(this.response));
};
xhr.open('GET', '/data.json', true);
xhr.send();
Read more at https://developer.chrome.com/apps/app_external
For those who are developing a Chrome Extension, you need to do it a little different according to this site: https://developer.chrome.com/extensions/xhr (I haven't tested this.);
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(JSON.parse(this.response));
};
xhr.open('GET', chrome.extension.getURL('/data.json'), true);
xhr.send();
Edit
If you want to use jQuery (as in the example that you found.):
$.getJSON('data.json', function(data) {
console.log(data);
});

Categories