0

I am trying to create a chrome extension that injects some content into product pages on a particular site. Currently my content.js only runs if I manually refresh the tab on a matching page. I need it to run automatically every time the user navigates to a matching page.

manifest.json

{
    "manifest_version": 2,
    "name": "My Test",
    "version": "1.0",
    "description": "My Test POC",
    "icons": {
        "128": "/images/128x128_elevated_b_icon_purp.png",
        "48": "/images/48x48_elevated_b_icon_purp.png",
        "16": "/images/16x16_elevated_b_icon_purp.png"
    },
    "page_action": {
        "default_icon": "/images/16x16_elevated_b_icon_purp.png",
        "default_title": "My Test"
    },
    "background": {
        "scripts": ["/scripts/eventPage.js"],
        "persistent": true
    },
    "content_scripts": [
        {
            "matches": ["https://www.tesco.com/groceries/en-GB/products/*"],
            "run_at": "document_idle",
            "js": ["/scripts/libs/jquery.min.js", "/scripts/content.js"],
            "css": ["content.css"]
        }
    ],
    "permissions": [
        "tabs",
        "https://www.tesco.com/groceries/en-GB/products/*"
    ]
}

eventPage.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.todo == "showPageAction") {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.pageAction.show(sender.tab.id);

            alert('eventPage.js');
        });
    }
});

content.js

chrome.runtime.sendMessage({todo: "showPageAction"});

alert('content.js');

$(document).ready(function() {
    var productName = $('head title').text().replace(' - Tesco Groceries', '');

    console.log('Product Name: ' + productName);

    //Do stuff


});
Mark Seymour
  • 111
  • 4
  • 16
  • See [this answer](https://stackoverflow.com/a/39508954). – wOxxOm May 06 '20 at 08:52
  • Thank you for the link. I've done some digging, and now I am using chrome.webNavigation.onHistoryStateUpdated to send messages to the content.js that I use to trigger my content actions. My only problem now is that it does this for all pages, not just those that match my rules in the manifest for content_scripts. – Mark Seymour May 06 '20 at 10:28
  • You can specify url filter in webNavigation's addListener, see the documentation and an [example](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/onCompleted#Examples). – wOxxOm May 06 '20 at 11:04

0 Answers0