Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...