Thumbnails From External Sources Are Not Appearing In Random Posts Widget

﹥>﹥吖頭↗ 提交于 2019-12-12 09:17:43

问题


Here is the jsfiddle for my question.

http://jsfiddle.net/jaribhai/wncwqerj/1/

This is the code.

// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
    maxResults = 4,
    summaryLength = 170,
    noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
    containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
    var i = arr.length, j, temp;
    if (i === 0) return false;
    while (--i) {
        j = Math.floor(Math.random() * (i + 1));
        temp = arr[i];
        arr[i] = arr[j]; 
        arr[j] = temp;
    }
    return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
    var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
    if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults)); 
    // document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
    add_script(homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
    var link, summary, img,
        ct = document.getElementById(containerId),
        entry = shuffleArray(json.feed.entry),
        skeleton = "<ul>";
    for (var i = 0, len = entry.length; i < len; i++) {
        summary = ("summary" in entry[i]) ? (entry[i].summary.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '&hellip;' : "";
        img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
        for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
            link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
        }
        skeleton += '<li>';
        skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
        skeleton += '<a href="' + link + '">' + entry[i].title.$t + '</a><br>';
        skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
    labels = [];
for(var z = 0, zen = tags.length; z < zen; ++z) {
    labels.push('<a href="' + homePage + '/search/label/' + encodeURIComponent(tags[z].term) + '?max-results=20" rel="tag">' + tags[z].term + '</a>');
}
skeleton += labels.join(', ');
skeleton += '</small>';
        skeleton += '<span class="clear"></span></li>';
    }
    ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
function add_script(url) {
    var s = document.createElement('script');
    s.src = url;
    document.getElementsByTagName('head')[0].appendChild(s);
}

This is the demo of random posts widget from blogger. It is showing thumbnails from only those posts where images are linked from blogger but its not showing thumbnails for those images which are linked from external sources. What can I do so that images from external hosts also appear in the thumbnails.


回答1:


As the image is hosted externally , it won't be present in the media$thumbnail field of the feed. We will have to parse the HTML content of the post to extract the URL of the image. Two changes need to be done to make this work -

Firstly switch from the summary feed to default feed URL. This is necessary for getting the HTML content of the post (summary feed only contains the limited summary text of the post not the full HTML). Change every instance of

/feeds/posts/summary?alt=json-in-script

to

/feeds/posts/default?alt=json-in-script

Secondly change the condition for finding the image in the post from

img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;

to

if ("media$thumbnail" in entry[i]) {
  img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
  img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
  img = noImageUrl;
}

Refer to the working example below -

// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
  maxResults = 4,
  summaryLength = 170,
  noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
  containerId = 'random-post-container';

// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
  var i = arr.length,
    j, temp;
  if (i === 0) return false;
  while (--i) {
    j = Math.floor(Math.random() * (i + 1));
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  return arr;
}

// Get a random start index
function createRandomPostsStartIndex(json) {
  var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
  if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
  // document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
  add_script(homePage + '/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}

// Widget's main function
function randomPosts(json) {
  var link, summary, img,
    ct = document.getElementById(containerId),
    entry = shuffleArray(json.feed.entry),
    skeleton = "<ul>";
  for (var i = 0, len = entry.length; i < len; i++) {
    summary = ("content" in entry[i]) ? (entry[i].content.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '&hellip;' : "";
    if ("media$thumbnail" in entry[i]) {
      img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
    } else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
      img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
    } else {
      img = noImageUrl;
    }
    for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
      link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
    }
    skeleton += '<li>';
    skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
    skeleton += '<a href="' + link + '">' + entry[i].title.$t + '</a><br>';
    skeleton += '<span>' + summary + '</span>';



    // Show all post labels ...
    skeleton += ' <small>';
    var tags = entry[i].category,
      labels = [];
    for (var z = 0, zen = tags.length; z < zen; ++z) {
      labels.push('<a href="' + homePage + '/search/label/' + encodeURIComponent(tags[z].term) + '?max-results=20" rel="tag">' + tags[z].term + '</a>');
    }
    skeleton += labels.join(', ');
    skeleton += '</small>';



    skeleton += '<span class="clear"></span></li>';
  }
  ct.innerHTML = skeleton + '</ul>';
}

// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');


/**
 * `document[dot]write` is disallowed in JSFiddle envioriment and might break your fiddle.
 */

function add_script(url) {
  var s = document.createElement('script');
  s.src = url;
  document.getElementsByTagName('head')[0].appendChild(s);
}
body {
  margin: 0;
  padding: 50px;
  background-color: white;
  font: normal normal 11px/1.4 Arial, Sans-Serif;
  color: black;
}
#random-post-container {
  width: 400px
}
#random-post-container ul,
#random-post-container li {
  margin: 0;
  padding: 0;
  list-style: none;
  overflow: hidden;
}
#random-post-container img {
  display: block;
  float: left;
  border: 1px solid;
  margin: 2px 7px 5px 0;
}
#random-post-container a {
  font-weight: bold;
  font-size: 110%;
}
#rancom-post-container .clear {
  display: block;
  clear: both;
}
<h2>Random Post</h2>
<div id='random-post-container'>Memuat&hellip;</div>


来源:https://stackoverflow.com/questions/34585558/thumbnails-from-external-sources-are-not-appearing-in-random-posts-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!