Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: How can I show the find bar and supply text for it?

I am making an extension that stores the selected text from the currently active webpage into localstorage, then when the user click on this selected text in my extension's popup, the extension will fire chrome.tabs.create and open the website where the selected text was selected. These functions work, but I don't know how to trigger the 'find' function when the new tab opens. I want the newly created tab to highly the selected text that my extension stored. I think there are two ways to do this...

  1. somehow trigger the 'find' function that the browser by default has. The one with 'Ctrl+F" or 'Command+F" triggers and insert the selected text in there

  2. edit the HTML of the newly created page by highlighting the selected text.

new_source = { "url" : tab[0].url, "title" : tab[0].title, "quote" : selectedQuote, "id" : idSource};
sources.push(new_source);
localStorage["sources"] = JSON.stringify(sources);

This is how I'm storing my information

like image 354
user1871515 Avatar asked Dec 04 '12 23:12

user1871515


1 Answers

You can't trigger Chrome's native find dialog, but you can invoke window.find(). The main differences between the native dialog and find() are

  1. find() only highlights one of the matches in the page, whereas the native dialog highlights all. To be precise, find() will begin by highlighting the match nearest to the top of the document, and repeated invocations will move it down the page.

  2. find() will highlight the selected text in with the default blue color, whereas Chrome's find dialog highlights its matches in orange. However, this can be mimicked by modifying the background CSS property of the ::selection pseudo-class.

Depending on your use case this might be sufficient.

However, if you want to highlight a specific quote on the page, and need to account for possible duplicates of that quote, then it's a bit more tricky, and I'm not sure it can be done perfectly. You'll want to get the precise location of the selected text using window.getSelection(), find a way to identify its startNode and endNode across page reloads (if they have ids, this is easy, but if not you'll have to resort to hacks), and then when the page is reopened, use Selection.addRange() to restore it.

like image 191
int3 Avatar answered Sep 19 '22 13:09

int3