Question

I'm writing the extension which will change layout of google in my browser. My script using external css file when browser shows google.com. And it works fine before I opening a new tag - css is cleared. How can I match my css only for google search page?

window.addEventListener("load", function() { myExtension.init(); }, false);

var myExtension = {
  init: function() {
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent)
      appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
    var messagepane = document.getElementById("messagepane"); // mail
    if(messagepane)
      messagepane.addEventListener("load", function(event) { myExtension.onPageLoad(event); }, true);

  },

  onPageLoad: function(aEvent) {
  var patt_g=new RegExp('google.com','g');
    Firebug.Console.log('Hide my ass started');
    this.doc = aEvent.originalTarget; // doc is document that triggered "onload" event

    CSSProvider.init();
   if(patt_g.test(this.doc.location.href)) {
        Firebug.Console.log('Hide my ass -> in');
        CSSProvider.loadCSS();
    }  else {
        Firebug.Console.log('Hide my ass -> out');
        CSSProvider.unloadCSS();
    }

    // add event listener for page unload 
    aEvent.originalTarget.defaultView.addEventListener("unload", function(event){ myExtension.onPageUnload(event); }, true);
  },

  onPageUnload: function(aEvent) {
  Firebug.Console.log('Hide my ass deleted');
    if(patt_g.test(this.doc.location.href) ) {
        Firebug.Console.log('Hide my ass -> out');
        CSSProvider.unloadCSS();
    }
  }

};


var CSSProvider = {
    init: function(){
        this.sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
                    .getService(Components.interfaces.nsIStyleSheetService);
        this.ios = Components.classes["@mozilla.org/network/io-service;1"]
                        .getService(Components.interfaces.nsIIOService);
        this.uri = this.ios.newURI("chrome://hms/content/style.css", null, null);
        this.isRegistered = this.sss.sheetRegistered(this.uri, this.sss.USER_SHEET)
    },
    loadCSS: function(){
        if(!this.isRegistered){
            this.sss.loadAndRegisterSheet(this.uri, this.sss.USER_SHEET);
        }
    },
    unloadCSS: function(){
        if(this.isRegistered){
            this.sss.unregisterSheet(this.uri, this.sss.USER_SHEET);
        }
    }
};
Was it helpful?

Solution

Don't load/unload the CSS file each time a tab is opened - adding a user stylesheet will always apply it to all existing tabs, unloading it will remove it from all tabs. Simply add the stylesheet when your extension loads and put the CSS rules in the stylesheet into a @-moz-document section:

@-moz-document domain(google.com)
{
  ...
}

Documentation: https://developer.mozilla.org/en/CSS/@-moz-document

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top