Take an article attachment snapshot of CSS media print page in a Zotero translator

Estimated reading time of this article: 2 minutes

A good Zotero translator should add an article snapshot as attachment. These snapshots are usually taken from the print version of the article since ads, navigation and so one are cut off. Short the print version shows only the essential article. Content management systems (CMS) use different techniques for print pages, e.g. the print page can be accessed with a /print suffix in the URL. Some CMS like Drupal work with CSS media type stylesheets. There, a print page uses a dedicated CSS print stylesheet. Example:

<link type="text/css" rel="stylesheet" media="all" href="default.css" />
<link type="text/css" rel="stylesheet" media="screen" href="screen.css" />
<link type="text/css" rel="stylesheet" media="print" href="print.css" />

How can the CSS media based print page be activated for an article snapshot?

I've written a helper function for my Zotero translator.

/**
* Manipulates the DOM document tree by switching CSS media from screen to print.
*
* @param {element} doc Document DOM tree (Remember: JavaScript parameters are passed by reference)
* @return {element} document Document DOM tree
*/
function switchDomMediaPrint(doc) {
  var nodes = doc.getElementsByTagName('link');
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].getAttribute('media') == 'print') {
      nodes[i].setAttribute('media', 'all');
    } else if (nodes[i].getAttribute('media') == 'screen') {
      nodes[i].setAttribute('media', 'DISABLE');
    }
  }
  return doc;
}

I've used the function the following way in my translator where doc contains the document DOM tree:

// Use the CSS media print stylesheet for the snapshot.
switchDomMediaPrint(doc);
newItem.attachments.push({title: newItem.publicationTitle + " Article Snapshot", document:doc});