Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension communicate with rest web service

I am new in chrome extension, and I am developing an extension that will communicate to my rest web service. My rest web service will return a json string. What i wanted to do is to call my web service, get the response json.

Currently I have this in my background.js:

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.getSelected(null,function(tab) {
        var link = tab.url;
        alert(link);
    });
});

My plan is when user clicked on the icon extension, the current tab url will be sent to my web service, and it will get response json.

My question is, what is the code or syntax that does something like webclient.downloadstring in C#? Or how can I communicate with the web service?

like image 375
Wylan Osorio Avatar asked Nov 23 '14 16:11

Wylan Osorio


People also ask

How do I communicate with Chrome extensions?

If you only need to send a single message to another part of your extension (and optionally get a response back), you should use the simplified runtime. sendMessage or tabs. sendMessage. This lets you send a one-time JSON-serializable message from a content script to extension, or vice versa, respectively.

Can Chrome extensions send data?

Since Chrome extensions are event-driven because of their architecture, once the injected scripts have access to the page's variables and functions, they can pass it to the content script. The content script then passes the these objects to the background page.


1 Answers

The API you're looking for is called XMLHttpRequest (also known as "AJAX"). Read the documentation at https://developer.chrome.com/extensions/xhr for more information.

Here's an example:

chrome.browserAction.onClicked.addListener(function(tab) { 
    var link = tab.url;
    var x = new XMLHttpRequest();
    x.open('GET', 'http://example.com/?whatever=' + link);
    x.onload = function() {
        alert(x.responseText);
    };
    x.send();
});

Note. The XMLHttpRequest API is asynchronous. This means that you cannot do something like this:

...
var result;
x.onload = function() {
    result = x.responseText;
};
x.send();
alert(result); // Does not behave as you expect!
like image 153
Rob W Avatar answered Oct 04 '22 14:10

Rob W