Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
47
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@5a3i

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

<問題・課題>

  • 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();
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
47
Help us understand the problem. What are the problem?