Last active
September 6, 2019 02:17
-
-
Save taketakeyyy/e0e312e8c7307977f647394294467fdd to your computer and use it in GitHub Desktop.
XMLHttpRequestのサンプル。非同期処理で指定したURLのDOMを取得する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
CodePenなどから実行してもCORS制約によりおそらくDOMは取得できない。PromiseStatusがPending状態から進まない。
Chrome拡張でQiitaページからQiitaへのデータ取得はOK。
動作を確認するために、このページでF12を押して、Consoleに上記のコードをコピペして実行しても、PromiseStatusがPending状態から進まないことがわかる。
一方、QiitaページでF12を押して、同様にコードをコピペして実行すると、DOMが取得できる。