简体   繁体   中英

Twitter oEmbed cross-origin request blocked

I'm trying to use the Twitter oEmbed API to make a request for an embedded tweet. The code is super-simple right now:

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("GET", "https://api.twitter.com/1/statuses/oembed.json?id=507185938620219395", true);
xmlhttp.send();

I'm getting a Cross-Origin Request Blocked error in Firefox. What am I doing wrong?

The answer is "use jsonp"

$.ajax({
  type:     "GET",
  url:      "http://api.twitter.com/1/statuses/oembed.json?id=507185938620219395",
  dataType: "jsonp",
  success: function(data){
    console.log(data);
  }
});

https://ctrlq.org/code/19933-embed-tweet-with-javascript

This one is a workaround for fixing the error

 <!-- Written by Amit Agarwal amit@labnol.org Paste this anywhere between the body tag --> <style> #tweet { width: 400px !important; } #tweet iframe { border: none !important; box-shadow: none !important; } </style> <div id="tweet" tweetID="515490786800963584"></div> <script sync src="https://platform.twitter.com/widgets.js"></script> <script> window.onload = (function(){ var tweet = document.getElementById("tweet"); var id = tweet.getAttribute("tweetID"); twttr.widgets.createTweet( id, tweet, { conversation : 'none', // or all cards : 'hidden', // or visible linkColor : '#cc0000', // default is blue theme : 'light' // or dark }) .then (function (el) { el.contentDocument.querySelector(".footer").style.display = "none"; }); }); </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM