Tim Bray does a good job explaining what the +1 button is and why we should care.
How it works
The extension manifest declares which script to embed into the host page, and what pages should use the extension:
matchesSelectorthis was fairly easy. However, it wasn't as simple as "start extension, scan page, insert new HTML".
Twitter's web app (aka New Twitter) is all up in the DHTML/AJAX/HTML5/FancyShmancy. All of those tweets come in after the main web app bootstraps. The extension, therefore, can't just scan the HTML page looking for the right markup, as the page is essentially blank at first!
Therefore, I needed to wait until after Twitter loaded tweets and displayed them on the page. Luckily, the DOM has a great event for this:
DOMNodeInserted. The extension can listen for those events from the main web page's DOM, as the content script from the extension shares the same DOM as the web page.
The third challenge was handling the never ending scrolling of Twitter's home page. I love the implementation as a user, but it provided a bit of a challenge for this extension.
Normally, the Google +1 code scans the web page, finds the markup, and then replaces it with its own <iframe> which contains the button. By default, this scan is performed once. However, because Twitter can add tweets to a page as the user scrolls, those new tweets won't get their +1 buttons.
You'd think you could simply call
gapi.plusone.go()after every time I detect new tweets via
DOMNodeInsertd. Unfortunately, a content script can't access the main web page's variables. Because I injected the Google +1 code into Twitter's web page, the
gapivariable isn't visible in the content script.
Check out the code for the Tweets +1 extension, and I highly recommend the Chrome Extensions Samples for real working code. Of course, install the extension and start +1'ing some tweets!