Skip to content

Instantly share code, notes, and snippets.

@SputterPuttRedux
Last active June 6, 2016 16:28
Show Gist options
  • Save SputterPuttRedux/cb84a1a5d914eace0a78ab84f2f46eeb to your computer and use it in GitHub Desktop.
Save SputterPuttRedux/cb84a1a5d914eace0a78ab84f2f46eeb to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name See YouTube ViewCount Inline
// @namespace http://tampermonkey.net/
// @version 0.1
// @description A small script to allow one to see the number of views a youtube search result
// has in a google search results set. To use this script, obtain a YouTube API key,
// then on line 40 below paste your API key over the YOUR_API_KEY_STRING text.
// @author SputterPuttRedux
// @match https://www.google.com/search?*
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @include https://www.google.com*
// ==/UserScript==
function getYouTubeViewCount(elem){
function addViewCountToDom(){
var urlString = elem.siblings().find("cite").html();
if(urlString && urlString.includes('youtube.com')){
var videoId = videoIdFromUrlString(urlString);
var formattedUrl = formattedUrlForApiCall(videoId);
$.ajax({
type: 'GET',
url: formattedUrl,
dataType: 'html'
}).done(function(response){
var respObj = JSON.parse(response);
var viewCountNum = respObj.items[0].statistics.viewCount;
elem.append(" | Views: " + commaFormattedNumber(viewCountNum));
});
}
}
function commaFormattedNumber(numStr){
return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function formattedUrlForApiCall(videoId){
return 'https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + videoId + '&key=YOUR_API_KEY_STRING';
}
function videoIdFromUrlString(urlString){
return urlString.split("?v=").pop();
}
addViewCountToDom();
}
waitForKeyElements (".slp", getYouTubeViewCount);
@SputterPuttRedux
Copy link
Author

SputterPuttRedux commented Jun 2, 2016

One line 38, you'll see that i reference a YouTube API key. Here are instructions for how to get your own. Copy and paste your key after &key= on that line and voila.

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