Simple Firefox Content Scripts
This post includes notes from creating my first Firefox add-on, a simple plugin that modifies my Pinboard homepage. The resulting code is also on Gitlab.
Goal
Streamline the post-processing of bookmarks added to Pinboard using IFTTT. I have a recipe that posts new Twitter favorites to IFTTT. The following tags are added to the new bookmark:
via:IFTTT via:Twitter via:@{{UserName}} via:{{LinkToTweet}}
The two {{ }}
placeholders are expanded with data from the tweet. In some cases I need to
revisit the tweet for context as I clean up the bookmark, add tags, or fix an
incorrect link. I needed a script that would automatically extract the URL from
the right "via:" tag and add a link to the page.
Misc. notes
cfx xpi
to build the plugin .xpi file. Use the Extension Auto-Installer to streamline development:
cfx xpi ; wget --post-file=pinboard-http-tags.xpi http://localhost:8888/
console.log()
doesn't work out of the box. Open about:config
and add a new
key "extensions.sdk.console.logLevel" set to "info". See "console".
lib/main.js:
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*.pinboard.in",
contentScriptFile: data.url("content-script.js")
});
data/content-script.js:
var bookmarks = document.querySelectorAll('.bookmark');
for (var i = 0, bookmark_count = bookmarks.length; i < bookmark_count; i++) {
var bookmark = bookmarks[i];
var tags = bookmark.querySelectorAll('.tag');
for (var j = 0, tag_count = tags.length; j < tag_count; j++) {
var tag = tags[j].textContent;
if (!tag.match(/^via:https?:\/\//)) {
continue;
}
var href = tag.substr(4);
var newLink = document.createElement('a');
newLink.href = href;
newLink.textContent = href;
newLink.target = '_blank';
bookmark.appendChild(document.createElement('br'));
bookmark.appendChild(newLink);
}
}
document.querySelectorAll
doesn't return a NodeList. :(
Result
pinboard-http-tags on Gitlab.