Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

<問題・課題>

  • 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で設定したドメインからのみアクセス可能

  1. 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();
5a3i
Housmartでエンジニアをやっております。
https://kawlu.com/
housmart
ハウスマートはテクノロジーとデザインと不動産の専門知識を融合させ、「住」の概念をもっと自由なものに進化させます。
http://techblog.housmart.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした