Search code examples
firefoxfirefox-addonadd-on

Firefox addon requires additional refresh to work


I have started developing an addon which would work on package.json of a Github repo. On loading the addon, it requires an additional page refresh for the addon to take effect instead of applying the border as soon as the url is recognized.

manifest.json

{
  "manifest_version": 2,
  "name": "Border It",
  "version": "0.0.1",
  "permissions": ["activeTab", "tabs", "https://github.com/*"],
  "content_scripts": [
    {
      "matches": ["https://github.com/*/package.json"],
      "js": ["src/scripts/borderify.js"],
    }
  ]
}

borderify.js

document.body.style.border = '5px solid red';

What am I doing wrong?


Solution

  • GitHub updates page content dynamically, so you need to run your script on every GitHub pages ("matches": ["https://github.com/*"]) and observe the location change. Here is more hints: Event when window.location.href changes

    (updated) Example implementation based on MutationObserver:

    {
      "manifest_version": 2,
      "name": "Border It",
      "version": "0.0.1",
      "permissions": [
        "activeTab",
        "tabs",
        "https://github.com/*"
      ],
      "content_scripts": [
        {
          "matches": ["https://github.com/*"],
          "js": ["borderify.js"]
        }
      ]
    }
    
    function onLocationChanged() {
      if (/\/package.json([?#]|$)/.test(location.pathname))
        document.body.style.border = '5px solid red';
      else
        document.body.style.border = '';
    }
    onLocationChanged(); // executed when the page is initially loaded
    
    let lastUrl;
    
    const observer = new MutationObserver(mutations => {
      // executed on any dynamic change in the page
      if (location.href == lastUrl)
        return;
      lastUrl = location.href;
      onLocationChanged();
    });
    const config = {
      childList: true,
      subtree: true
    };
    observer.observe(document.body, config);