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?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With