Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to pull data from an API in a Chrome extension

I'm trying to create a Chrome extension that pulls and manipulates data from Metacritic. I found this pretty great API online that would let me send a GET request for the data I need and return it in a JSON. However, it doesn't look like I can do it directly in JS.

Is there any way to run the API request in the extension? I saved the URL as a variable in the JS file and formatted it so that all it would take is plugging it into the request... if I could figure out how it would work.

Edit: After thinking, maybe one way to solve it would be to run a script in one of the available languages (like Ruby) FROM the Javascript file in the extension... Is this possible?

like image 274
nao Avatar asked Sep 10 '25 02:09

nao


1 Answers

The main reason you may not be able to access an API from javascript is the same-origin security restriction.

Chrome extensions can request permissions to access a given domain and bypass those restrictions, documentations of this can be found at: https://developer.chrome.com/extensions/xhr#requesting-permission

Adding the following to your extensions manifest file should do the trick:

"permissions": [
    "https://byroredux-metacritic.p.mashape.com/"
],

Once you've done that you should be able to access the API using any normal XHR client from your extensions javascript (be careful for any security concerns). The most common API for XHR is probably the jQuery method $.ajax.

For example something like:

$.ajax({
    url: "https://byroredux-metacritic.p.mashape.com/find/game",
    method: "POST",
    headers: {
        "X-Mashape-Key": API_KEY
    },
    data: {
        platform: 1,
        retry: 4,
        title: "The Elder Scrolls V: Skyrim"
    },
    dataType: "json",
    success: function(data) { console.log(data) }
})

(Note: none of this code has been tests).

like image 123
Hargo Avatar answered Sep 12 '25 18:09

Hargo