LoginSignup
1

More than 5 years have passed since last update.

XMLHttpRequestを使う

Posted at

はじめに

FirefoxのaddonからHTTPのリクエストでデータを送信します。

XMLHttpRequestを使ったサンプル

  • XMLHttpRequestを使うとリクエストを送信できます。
  • Query parameter で渡す値は encodeURIComponent で encode します
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のqueryパラメータで値を取得します。

  • UTF-8で URLEncode した parameterを取得します。
  • Access-Control-Allow-Origin: * のヘッダーを指定します。
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"); 
    // encoding が動作しなかった時用
    String query = request.getQueryString();
    if (query.indexOf("arg0=")>0) {
        arg0 = query.substring(query.indexOf("arg0=")+5);
        arg0 = URLDecoder.decode(arg0, "UTF-8");
    }
    // 省略
}

Access-Control-Allow-Originについて

Access-Control-Allow-Origin がないと Firefoxの console に以下のメッセージがでます。

  • エラーは出てますがサーバー側ではリクエストは受け付けられ処理されます。
  • エラーは応答メッセージを処理しないことを示しているようです。
console
クロスオリジン要求をブロックしました: 同一生成元ポリシーにより、
http://sample/?arg0=name にあるリモートリソースの読み込みは拒否されます 
(理由: CORS ヘッダー ‘Access-Control-Allow-Origin’ が足りない)。

参考

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1