javascriptgoogle-chrome-extensionpushover

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:

Many thanks in advance for any help.


Solution

  • 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.