简体   繁体   中英

Chrome extension search for string then perform something

Through research and other bits of code I've almost cobbled together my own chrome extension which will use the Pushover notification service to send an alert should a page load in chrome which has certain text in it.

I've managed to get my background.js to send an alert once any page has finished loading:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab){
if (changeInfo.status == 'complete') {
chrome.tabs.sendRequest(tab.id, {method: 'selection'}, 
function (text) { push_message(tab, text,  
'');

And I've got my little bit of java code to find a string

if (~document.body.textContent.indexOf('cricket')) { alert("page contains string"); }

But I can't seem to get the two to work together. I've read mixed reports about placing the finding string java in contentscript.js? Also I preferably want my code to be able to search for multiple strings. So it would work like this:

  • Page finishes loading
  • Javascript searches page for the term cricket or football
  • If it finds either of these terms it fires the code to send the push notification (my first bit of code above which is currently in background.js)

Many thanks in advance for any help.

In your manifest.json you can do something like

"content_scripts": [
{
  "matches": ["<all_urls>"],
  "js": ["someContentScript.js"],
  "run_at": "document_start",
  "all_frames": false,
}]

And then in your content script you can do the page scrapping once you have received to the load or DOMContentLoaded event.

Once you detect your string (football or cricket) you can send a message to your background page using the messaging APIs. Look at chrome.runtime.sendMessage API. I think there is another way but I am not sure.

Now once you are in your background.js code, you can call your push API.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM