Bookmarklet: copy a link for Twitter and editors

[2011-05-21] bookmarklet, dev, hack, blogging
(Ad, please don’t block)
Update 2011-09-27: Automatically remove parts of the title, add a Twitter name, add a hashtag.

Problem: You have found an interesting web page and would like to copy its link, for use with Twitter or an editor. That means you need to perform several steps: First, you copy the URL. Second, you go back to copy the title (which might be tricky to get at). Third, you construct the link from the copied pieces.

Note that Twitter provides a bookmarklet for publishing a link, but it relies on the Twitter web application which does not handle multiple accounts well. The solution shown here can be used with Twitter desktop applications.

Features

The bookmarklet presented in this post has the following features:
  • It opens in a new window and does not change the page to be linked. Note: the URL will be replaced by the bookmarklet code. In some browsers you can undo that change (Firefox: go to address bar, hit Escape).
  • It offers three formats:
    • Twitter: pageTitle @TwitterName URL #hashtag
      The Twitter name and the hashtag are optional and have to be specified per host (see below).
    • HTML source code: <a href="URL">title</a>
    • An actual HTML link that you can copy in your web browser and paste to WYSIWYG editors such as the Blogger post editor.
  • Any text that you have selected will also be shown on the result page.
  • Configuration: Per host, you can configure what text to remove from the title and what Twitter name or hashtag to add. Example:
        var hosts = {
            "www.macrumors.com": {
                re:   /^(.*) - Mac Rumors$/,
                twit: "@MacRumors",
                htag: "#mac"
            }
        }
    
    Explanation: If the host is www.macrumors.com then
    • the suffix “ - Mac Rumors” is removed from the title.
    • the Twitter name @MacRumors is added before the URL.
    • the hashtag “#mac” is appended after the URL.

Installation and usage

Installation:
  • Try it out: Click the link below right now, if you want to see how the bookmarklet works.
  • Install: Drag this link to your bookmarks.
  • Tip: use a keyword for quick access.
Usage:
  1. Go to an interesting page.
  2. Optional: select text that you want to copy together with the link.
  3. Invoke the bookmark.
You can download the source code on GitHub.

Related reading

  1. Bookmarklets: simple plugins for your browser
  2. Implementing bookmarklets in JavaScript [comprehensive how-to]