How to change the color of icon according to user login

后端 未结 2 622
遇见更好的自我
遇见更好的自我 2021-01-07 11:52

I have made an extension to my website.It navigates to my home page which is my login page.When the user log on to my site,the extension icon must appear green and when user

2条回答
  •  再見小時候
    2021-01-07 12:39

    One solution is to communicate the login status from your webpage to your extension (as explained here).


    From your webpage you have to send messages to the extension to inform it about the user's login status.

    • Once the user successfully logs in, make sure you let the extension know:

      chrome.runtime.sendMessage(
          ,
          {status: 'LOGGED_IN'});
      
    • Once you detect that the user's session has ended (either expired or due to manually logging out), make sure you let the extension know:

      chrome.runtime.sendMessage(
          ,
          {status: 'LOGGED_OUT'});
      

    From your extension listen for messages from the webpage and update accordingly, e.g. change the extension's icon. You'll need two icons (e.g. red.png for indicating logged-out user and green.png for indicating logged-in user) and the source code below:

    background.js:

    var url = '';
    
    // Listen for external messages (messages from web-pages).
    chrome.runtime.onMessageExternal.addListener(function (msg, sender) {
      if (sender.url === url) {
        // OK, this page is allowed to communicate with me.
        if (msg.status === 'LOGGED_IN') {
          // Cool, the user is logged in.
          chrome.browserAction.setIcon({path: 'green.png'});
        } else if (msg.status === 'LOGGED_OUT') {
          // How sad, the user is logges out.
          chrome.browserAction.setIcon({path: 'red.png'});
        }
      }
    });
    

    manifest.json:

    {
      "manifest_version": 2,
      "name":    "Test Extension",
      "version": "0.0",
    
      "background": {
        "persistent": false,
        "scripts": ["background.js"]
      },
    
      "browser_action": {
        "default_title": "Test Extension",
        "default_icon": "red.png"
      },
    
      "externally_connectable": {
        "matches": [""]
      }
    }
    

提交回复
热议问题