Here is an example of a Google Chrome extension that searches for a specific word in the active page:
- Create a new folder for the extension and create the following files inside it:
manifest.json
: This file defines the basic metadata and permissions of the extension.
{ "manifest_version": 2, "name": "Word Search Extension", "description": "Searches for a specific word in the active page", "version": "1.0", "permissions": ["activeTab"], "background": { "scripts": ["background.js"] }, "browser_action": { "default_icon": "icon.png", "default_title": "Word Search Extension" } }
icon.png
: This is the icon of the extension that will be displayed in the browser toolbar.background.js
: This file contains the background script of the extension, which runs in the background and listens for events.
chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript({ code: ` if (typeof word !== void 0) { word = prompt("Enter the word to search:"); } else { let word = prompt("Enter the word to search:"); } if (word) { let highlights = []; let textNodes = document.querySelectorAll("*"); textNodes.forEach(node => { let nodeText = node.innerText; if(nodeText !== void 0){ if(nodeText.trim().length > 0){ let searchIndex = nodeText.indexOf(word); while (searchIndex !== -1) { let range = document.createRange(); range.setStart(node, 0); range.setEnd(node, 1); highlights.push(range); searchIndex = nodeText.indexOf(word, searchIndex + 1); } } } }); highlights.forEach(range => { let highlight = document.createElement("mark"); highlight.style.backgroundColor = "yellow"; highlight.appendChild(range.extractContents()); range.insertNode(highlight); }); } ` }); });
- Load the extension in Google Chrome:
- Open Google Chrome and type
chrome://extensions
in the address bar. - Enable the "Developer mode" toggle in the top right corner.
- Click the "Load unpacked" button and select the folder containing the extension files.
- Test the extension:
- Click the extension icon in the browser toolbar.
- A prompt will appear asking you to enter the word to search.
- Enter the word and click "OK".
- The extension will highlight all the occurrences of the word in the active page.
This is a very basic example of a Google Chrome extension that searches for a specific word in the active page. You can customize and expand the functionality of the extension by adding more features, such as options to customize the search behavior or the highlight style, or by integrating with other APIs or services. You can learn more about developing Google Chrome extensions in the Google Chrome Developer Documentation.