Shaarli and external links in a new tab

Let´s suppose you want to use Shaarli. And let´s suppose you would like to use version 0.10.4

You will notice that links are opened in the same tab of Shaarli. There is a specific plugin that can be used to have those links opened in a new tab: shaarli-urlextern

Once installed you might notice that Shaarli stops working (blank empty page) when the plugin is activated

The plugin is made of three files:

 - urlextern.js
 - urlextern.meta
 - urlextern.php

The file we need to edit is urlextern.php. The file content is as follows:

<?php
/**
 * Shaarli urlextern Plugin
 *
 * @author Jeff Sacco
 * @link
 */

use Shaarli\Plugin\PluginManager;

/**
 * Hook render_footer.
 * Executed on every page redering.
 *
 * Template placeholders:
 *   - text
 *   - endofpage
 *   - js_files
 *
 * Data:
 *   - _PAGE_: current page
 *   - _LOGGEDIN_: true/false
 *
 * @param array $data data passed to plugin
 *
 * @return array altered $data.
 */
function hook_urlextern_render_footer($data)
{
    // List of plugin's JS files.
    // Note that you just need to specify CSS path.
    $data['js_files'][] = PluginManager::$PLUGINS_PATH . '/urlextern/urlextern.js';
    return $data;
}

/**
 * This function is never called, but contains translation calls for GNU gettext extraction.
 */
function urlextern_translation()
{
    // meta
    t('Open external links in new tab/window');
}

Just remove this line: use Shaarli\Plugin\PluginManager; and Shaarli will start working as expected

Let´s imagine now that for some specific domains you actually want to open the link in the very same tab. In this case we need to modify the urlextern.js file

Original file:

var links = document.links;
for (var i = 0, linksLength = links.length; i < linksLength; i++) {
  if (links[i].hostname != window.location.hostname) {
      links[i].target = '_blank';
  }
}

In my case I wanted to open links pointing to alterego.ws in the same tab. So the file was modified as follows:

var links = document.links;
for (var i = 0, linksLength = links.length; i < linksLength; i++) {
  if (links[i].hostname != window.location.hostname) {
     if (links[i].hostname.toLowerCase().indexOf("alterego.ws") === -1) {
        links[i].target = '_blank’;
     }
  }
}

The line – if (links[i].hostname.toLowerCase().indexOf(“alterego.ws”) === -1) – checks if “alterego.ws” is contained in the URL and if it does then the page is opened in the same tab. If the string is not contained within the URL the next line is executed so the link opens in a new tab

Shaarli logo attribution: https://github.com/sebsauvage/Shaarli

Leave a Reply

Your email address will not be published. Required fields are marked *