Send data with HTTP request from addon of Firefox.
background.js
browser.contextMenus.create({
id: "name",
title: "get name",
contexts: ["selection"],
});
var name = "blue";
getting = browser.storage.local.get("name", function (value) {
name = value.name;
});
browser.contextMenus.onClicked.addListener((info, tab) => {
getting = browser.storage.local.get("name", function (value) {
name = value.name;
});
if (info.menuItemId === "name") {
url= "http://sample/?arg0=" + name;
doGet(url);
}
}
function doGet(url) {
console.log(url);
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
console.log(xhr.status);
};
xhr.onerror = () => {
console.log(xhr.status);
console.log("error!");
};
xhr.send();
}
Get the value with the query parameter of GET.
doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("text/html; charset=UTF-8");
} catch (UnsupportedEncodingException e1) {}
String arg0 = request.getParameter("arg0");
//For when encoding did not work
String query = request.getQueryString();
if (query.indexOf("arg0=")>0) {
arg0 = query.substring(query.indexOf("arg0=")+5);
arg0 = URLDecoder.decode(arg0, "UTF-8");
}
//abridgement
}
Without Access-Control-Allow-Origin, you will see the following message in the Firefox console:
console
Blocked cross-origin request:By same-origin policy
http://sample/?arg0=Loading of remote resources at name is denied
(Reason:CORS header ‘Access-Control-Allow-Origin ’is missing)。
https://developer.mozilla.org/ja/docs/Web/API/XMLHttpRequest https://developer.mozilla.org/ja/docs/Web/HTTP/HTTP_access_control