[JAVA] Use XMLHttpRequest

Introduction

Send data with HTTP request from addon of Firefox.

Sample using XMLHttpRequest

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();
}

Data reception in Servlet

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
}

About Access-Control-Allow-Origin

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)。

reference

https://developer.mozilla.org/ja/docs/Web/API/XMLHttpRequest https://developer.mozilla.org/ja/docs/Web/HTTP/HTTP_access_control

Recommended Posts

Use XMLHttpRequest
Use ActiveStorage!
Use AutosizingTextView
Use JavaFX / TextFormatter
Use ControlsFX / Validation
Let's use jcmd
[Java] Use Collectors.collectingAndThen
[Rails] Use jQuery
Use sassc directly