Skip to content

Instantly share code, notes, and snippets.

@taketakeyyy
Last active September 6, 2019 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taketakeyyy/e0e312e8c7307977f647394294467fdd to your computer and use it in GitHub Desktop.
Save taketakeyyy/e0e312e8c7307977f647394294467fdd to your computer and use it in GitHub Desktop.
XMLHttpRequestのサンプル。非同期処理で指定したURLのDOMを取得する
// popup.htmlからQiitaページのXHRテスト(CORS制約を突破できるか?)(できている!2019/09/06)
// Qiitaのプロフィールページからアイコン画像を取得する
const url = 'https://qiita.com/takey';
function get(url) {
return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "document";
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
let res = xhr.response
let ava = res.getElementsByClassName("newUserPageProfile_avatar")[0];
resolve( ava );
}
}
});
}
// CORS制約により、別サイトからQiitaサイトのデータを読み込もうとするとエラーが発生
// 参考: https://qiita.com/tomoyukilabs/items/81698edd5812ff6acb34
let promise1 = get(url);
promise1.then(function(ret){
console.log(ret);
}).catch(function(reason){
console.log(reason);
});
@taketakeyyy
Copy link
Author

taketakeyyy commented Sep 6, 2019

CodePenなどから実行してもCORS制約によりおそらくDOMは取得できない。PromiseStatusがPending状態から進まない。

Chrome拡張でQiitaページからQiitaへのデータ取得はOK。

動作を確認するために、このページでF12を押して、Consoleに上記のコードをコピペして実行しても、PromiseStatusがPending状態から進まないことがわかる。

一方、QiitaページでF12を押して、同様にコードをコピペして実行すると、DOMが取得できる。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment