Bookmarklet to extract the contents of the topmost visible post


(Jason Sachs) #1

Just wanted to share my solution to major frustration in copying a Discourse post into an Outlook 2007 message (cue numerous sad trombone noises). Perhaps it has other applications. This essentially does the following:

  • figures out the post id
  • finds the relevant <article> node and clones it
  • removes the enclosing <a> link from each image
  • opens a new document (about:blank) with Calibri as the font-family
  • takes the cloned node and appends it to the new document

If I use it in Chrome I can then copy the resulting document, then Paste Special → as HTML Format into Outlook 2007 and it has a reasonable similarity to the original Discourse post.

Firefox creates the new about:blank page correctly but doesn’t seem to get data into the Windows Clipboard in a way that Outlook understands formatting.

enjoy…

javascript:(function() {
  var url = window.location.href;
  var reply_id = window.location.pathname.match(/\/t\/[^/]*\/([0-9]+)(?:\/([0-9]+))?$/);
  if (reply_id)
  {
    reply_id = reply_id[2] || "1";
	var original_contents = document.querySelector('article#post_'+reply_id+' .topic-body .contents .cooked');
	
	var contents = original_contents.cloneNode(true);
	function unwrap(element) {
	  var fragment = document.createDocumentFragment();
      while (element.firstChild) {
        fragment.appendChild(element.firstChild);
      }
      element.parentNode.replaceChild(fragment, element);
	}
	contents.querySelectorAll('img').forEach(function(img){
	  unwrap(img.parentElement); /* remove containing <a> link */
	});

	var newdoc = window.open().document;
	newdoc.write("<!DOCTYPE html><html><head><style type='text/css'>.cooked { font-family: Calibri, sans-serif; }</style></head><body></body></html>");
	newdoc.close();
    newdoc.adoptNode(contents);	
	newdoc.body.appendChild(contents);
  }
}());

(Jeff Atwood) #2

Cool, could you add a screenshot of it doing its stuff here?


(Jason Sachs) #3

okie-dokey!

some test content follows below:

'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

(Jason Sachs) #4

…which results in:

and I will have to use my work PC later to post a screenshot of Outlook, if that’s what you meant.