0

I want to create a Chrome extension that executes some code when the user reloads a tab e.g. by hitting the reload button. I'm attempting to do this via the webNavigation API by listening for a transitionType of reload. However, I cannot seem to get it to work. Here's my code:

manifest.json

{
  "manifest_version": 2,
  "name": "Sample Extension",
  "description": "Sample Chrome Extension",
  "version": "1.0",
  "background": {
    "scripts": ["background.js"]
  },
  "permissions":[
    "webNavigation"
  ]
}

background.js

chrome.webNavigation.onCommitted.addListener(function(transitionType) {
    if (transitionType.status == "reload") {
        // code goes here e.g. a console log
        console.log("You reloaded");
    }
});

Any ideas where I'm going wrong? Also, should I put the executable code (shown here as an alert) in a separate .js file? Eventually it will play a sound.

ddly
  • 5
  • 2
  • Use of `alert()` should be avoided; if only to [provide compatibility with Firefox](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities#Additional_incompatibilities), but generally because blocking code doesn't play nice with Chrome APIs. For user-facing notifications use `chrome.notifications`, for debugging use `console.log` and friends (but be sure to [open the correct console](https://stackoverflow.com/questions/10257301/where-to-read-console-messages-from-background-js-in-a-chrome-extension)) – Xan Oct 16 '17 at 10:04

1 Answers1

1

As far as it seems to me from the documentation, transitiontype is a property of the Event, so try to correct your code as follows:

chrome.webNavigation.onCommitted.addListener(function(d) {
    if (d.transitionType == "reload") {
        // code goes here e.g. an alert
        alert("You reloaded");
    }
});

Note: this will also trigger the code if you click a link from your History

Shimon Brandsdorfer
  • 1,673
  • 9
  • 23
  • 1
    Nitpick: the argument passed to the callback isn't an "event" in the traditional JS sense; it's just a bunch of properties that the documentation calls `details`, with no association with or properties expected of the Event object itself (which is `chrome.webNavigation.onCommitted`). So I would recommend renaming `e` to something else to avoid confusion with DOM events. – Xan Oct 16 '17 at 09:55
  • @Xan, Right, I fixed it. – Shimon Brandsdorfer Oct 16 '17 at 15:29