51
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

<Chrome extension>クロスドメインで怒られたら(XMLHttpRequest)

Posted at

<問題・課題>

  • Chrome拡張開発でクロスドメインを使いたい(外部API使ってhogehogeしたい)けど、ブラウザから怒られる
errorの内容
XMLHttpRequest cannot load ------. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '--------' is therefore not allowed access.

<解決方法>

参考:https://developer.chrome.com/extensions/xhr
(本家のドキュメントより)

※※やることは2つ※※

  1. manifest.json > permissions の修正

  2. XMLHttpRequestの利用 ※ただし、1で設定したドメインからのみアクセス可能

  3. manifest.json > permissions の修正

manifest.json
"permissions": [
    "http://api.example.com/" // api.example.comを使いますよの宣言
  ],
  1. XMLHttpRequestの利用 ※ただし、1で設定したドメインからのみアクセス可能
hoghoge.js
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    // json を受け取る場合はparseしましょう
    var resp = JSON.parse(xhr.responseText);

    // innerHTMLは意図せずインジェクションするかもしれないのでinnerTextで回避
    document.getElementById("resp").innerText = xhr.responseText;
  }
}
xhr.send();
51
47
1

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
51
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?