Search code examples
google-chrome-extensionfirefox-addon-webextensions

Firefox WebExtension: Check if MY extension exists


Porting extension from Chrome into FF

Followed this tutorial (which works fine in Chrome): http://www.codingscripts.com/check-whether-user-has-a-chrome-extension-installed/

Sending message from webpage to extension: In (web)pagescript.js this has:

function IsExist(extensionId,callback){
chrome.runtime.sendMessage(extensionId, { message: "installed" },
function (reply) {
   if (reply) {
      callback(true);
   }else{
      callback(false);
   }
});
}

IsExist("Your extension id",function(installed){
if(!installed){
   alert("Please install extension ");
}
});

Receiving message from webpage in extension:

chrome.runtime.onMessageExternal.addListener(
function(req, sender, callback) {
if (req) {
if (req.message) {
   if (req.message == "installed") {
    callback(true);
   }
 }
}
return true;
});

What I'm trying to achieve

A couple of html pages on my website need to redirect back to the homepage when the extension is NOT installed. So those pages need to be able to figure out (on their own) if the extension is installed or not.

Error I'm getting when I open webpage

ReferenceError : chrome is not defined. (I also tried with browser.runtime.onMessageExternal but then it throws "browser" is not defined). Is there no way to do this similar to what can be done in Chrome ?


Solution

  • Thanks to all the comments this is what I came up with. (I had to go for document_end (altho comments advise document_start) cause I had other things going on in content_script.js

    In my add-on's content_script.js

    document.body.classList.add("plugininstalledblabla");
    

    In my add-on's manifest.json

     "content_scripts":
      [
        {
          "matches": ["*://*/*"],
          "all_frames": true,
          "js": ["content_script.js"],
          "run_at": "document_end"
        }
      ]
    

    in my website's main.js script

    $(window).on("load", function() { // !! Window onLoad cause : document_end -> DOM should be loaded here
    
        // Set
        $body = $('body');
        if(document.body.classList.contains("plugininstalledblabla")){
           console.log('addon is installed');
        } 
    });