Skip to content

Instantly share code, notes, and snippets.

@shu8
Last active April 16, 2017 11:07
Show Gist options
  • Save shu8/4d433dbb7729416d7555785994834f6e to your computer and use it in GitHub Desktop.
Save shu8/4d433dbb7729416d7555785994834f6e to your computer and use it in GitHub Desktop.
Userscript that expands links to Stack Overflow questions in Google Search
// ==UserScript==
// @name Stack Overflow result expander in Google Search
// @namespace stackexchange.com/users/4337810/
// @version 1.0
// @description Expands links to Stack Overflow questions in Google Search
// @author ᔕᖺᘎᕊ (stackexchange.com/users/4337810/)
// @match *://*.google.com/search*
// @match *://*.google.co.uk/search*
// @require https://code.jquery.com/jquery-2.2.4.min.js
// @grant none
// ==/UserScript==
function addSearchResult($element, question_body, answer_author, answer_author_link, answer_body) {
$element.css({
'border': '1px solid gray',
'padding': '10px',
'box-shadow': '1px 1px 1px gray'
});
$element.find('.s div div:eq(0)').replaceWith("<div class='so-question'>" + question_body.split('\n').slice(0, 3).join('\n') + "</div>");
$element.find('.s div span:eq(0)').replaceWith("<hr><div class='so-answer'>" + answer_body + "<br> --<a href='" + answer_author_link + "'>" + answer_author + "</a></div>");
}
(function() {
'use strict';
setTimeout(function() {
var $results = $('.g');
$results.each(function() {
var href = $(this).find('a').attr('href');
if(href.indexOf('stackoverflow.com/questions/') > -1) {
var $result = $(this), id;
try {
id = href.split('/')[4];
} catch (e) {
return;
}
$.get(location.protocol+"//api.stackexchange.com/2.2/questions/"+id+"?order=desc&sort=activity&site=stackoverflow&filter=!4yoRaKOIy-2KA0N(t1Z)vZ_badwBMqW*Ypslv5", function(d) {
if(d.items[0].is_answered) {
var question_body = d.items[0].body;
if(d.items[0].accepted_answer_id) {
$.get(location.protocol+"//api.stackexchange.com/2.2/answers/"+d.items[0].accepted_answer_id+"?pagesize=1&order=desc&sort=votes&site=stackoverflow&filter=!)Q4RrMH0DC9PLfkTHbq7m*Bm", function(d2) {
var answer_body = d2.items[0].body;
var answer_author = d2.items[0].owner.display_name;
var answer_author_link = d2.items[0].owner.link;
addSearchResult($result, question_body, answer_author, answer_author_link, answer_body);
});
} else {
$.get(location.protocol+"//api.stackexchange.com/2.2/questions/"+id+"/answers?order=desc&sort=votes&site=stackoverflow&filter=!)Q4RrMH0DC9PLfkTHbq7m*Bm", function(d3) {
var answer_body = d2.items[0].body;
var answer_author = d2.items[0].owner.display_name;
var answer_author_link = d2.items[0].owner.link;
addSearchResult($result, question_body, answer_author, answer_author_link, answer_body);
});
}
}
});
}
});
}, 2000);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment