Finding text from a Firefox Extension

OK. Because this was confusing the hell out of me, I had to post about figuring it out.

Let’s say you’re a developer writing a Mozilla Firefox Extension that searches for text on a page (or rather, in a browser window). If you have a button that has the following functionality attached onclick:

var webBrowserFind = getBrowser().selectedBrowser.webBrowserFind;
webBrowserFind.searchString = TEXT_TO_SEARCH_FOR;
var result = webBrowserFind.findNext();

So, every time you click the button, it will search for the text in the current browser tab. Cool.

I did this, and it was working fine, until I wanted to find the second instance of the string on the page. I’d click it twice. Sometimes it would highlight the first instance again. Sometimes it would highlight the second instance. No real sign as to why, and as a kicker, it would never find past the first two instances of the string on the page.

Turns out that after a certain timeout, the nsIWebBrowserFind interface is going to reset which find instance it was at. This means that on the second click, it will find the first occurrence again. If you click twice within the timeout, you’ll get the second result. I didn’t see any mention of this in the documentation, and it’s not clear what the mechanism is that’s resetting the instance.

If you click really fast, you’ll get the third and fourth results. For once, getting frustrated and repeatedly clicking fast was the solution.

Hat tip to mfinkle and johnm of irc.mozilla.org#extdev for helping me find the nsIWebBrowserInterface in Seamonkey

2 thoughts on “Finding text from a Firefox Extension”

Leave a Reply