Skip to content

Instantly share code, notes, and snippets.

@mattandrews
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattandrews/90a567cd5561a15e7d39 to your computer and use it in GitHub Desktop.
Save mattandrews/90a567cd5561a15e7d39 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Show New Guardian Comments
// @namespace http://www.theguardian.com/
// @description Shows new comments
// @include http://www.theguardian.com/*
// @version 1
// @grant none
// ==/UserScript==
var prefix = 'gu-discussion-';
var delayTimer = 5000;
var getUUID = function () {
return guardian.config.page.shortUrl.replace('http://gu.com/', '');
};
var setLastVisited = function () {
window.localStorage.setItem(prefix + getUUID(), new Date());
}
var getLastVisited = function () {
return new Date(window.localStorage.getItem(prefix + getUUID())) || new Date();
};
var isFirstVisit = function () {
return !(window.localStorage.getItem(prefix + getUUID()));
}
var originalLastVisit = getLastVisited();
var highlightNewComments = function(newSince) {
function isNewer(d1, d2) {
if (d1.getTime() > d2.getTime()){
return true;
}
return false;
}
var count = 0;
var comments = document.querySelectorAll('.discussion__main-comments li.d-comment');
for (var i=0, l=comments.length; i<l; i++) {
var c = comments[i];
var timestamp = new Date(c.getAttribute('data-comment-timestamp'));
// if timestamp is newer than last viewed
if ( isNewer(timestamp, new Date(newSince)) ) {
c.style.backgroundColor = '#EEF6F9';
c.style.borderLeft = '10px solid #E2EEF3';
count++;
}
}
var commentCount = document.querySelector('.js-discussion-comment-count');
var commentCountHTML = commentCount.innerHTML;
commentCount.innerHTML = commentCountHTML + '<br />' + count + ' new';
};
var reloadOnPagination = function () {
var pagination = document.querySelectorAll('.pagination__list a');
for (var i=0, l=pagination.length; i<l; i++) {
pagination[i].addEventListener('click', function () {
window.setTimeout(function(){
highlightNewComments(originalLastVisit);
}, delayTimer);
});
}
};
window.setTimeout(function(){
if (!isFirstVisit()) {
highlightNewComments(originalLastVisit);
reloadOnPagination();
}
setLastVisited();
}, delayTimer);
@mattandrews
Copy link
Author

Todo list:

  • don't run on first load (otherwise it highlights everything)
  • prune the localStorage data occasionally (otherwise voracious readers will have tons of entries)
  • show a counter (next to total count?) of new stuff in a thread
  • make highlighting a bit prettier

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