David Tuite
David Tuite

Reputation: 22643

Prevent content script injection when private browsing activated?

I have a content script that I'd like to prevent from injecting itself when private browsing is enabled. I'm using the latest version of the Firefox add-on SDK (1.9).

I'm injecting content like this:

// lib/main.js
var pb = require('private-browsing');

pageMod.PageMod({
  include: "http://*",
  contentScriptFile: [self.data.url('jquery.min.js'),
                      self.data.url('content.js')],
  contentSriptWhen: 'start',
  onAttach: function(worker) {
    // do some stuff
  }
});

Wrapping the whole thing is an if statement doesn't work because the pageMode attachment is not evaluated for each injection. Entering and leaving private browsing doesn't trigger a reevaluation either.

if (!pb.isActive) {
  // the code I have above.
}

I could listen to the pb.on('start') event but I don't think there's a way to unattach pagemods. I could probably no-op the content script if private browsing mode is enabled but that seems like a hack which could lead to security concerns down the road.

What's the correct way to do this?

Upvotes: 0

Views: 279

Answers (1)

ZER0
ZER0

Reputation: 25322

There is a destroy method:

https://addons.mozilla.org/en-US/developers/docs/sdk/latest/packages/addon-kit/page-mod.html#destroy%28%29

It's important to note that if you made some changes to the existing pages you have to manually remove them.

So, you could have something like:

const pb = require('private-browsing');
const { PageMod } = require('page-mod');

var mod = null;

var options = {
  include: "http://*",
  contentScriptFile: [self.data.url('jquery.min.js'),
                      self.data.url('content.js')],
  contentSriptWhen: 'start',
  onAttach: function(worker) {
    // do some stuff
  }
}

if (!pb.isActive)
  mod = PageMod(options);

pb.on("start", function(){
  if (mod) {
    mod.destroy();
    mod = null;
  }
})

pb.on("stop", function() {
  if (!mod) {
    mod = PageMod(options);
  }
})

Didn't test, but just to give to you a rough idea. I'm not sure that create/destroy the PageMod every time is a good thing.

Note original post on mozilla-labs-jetpack mailing list, copied the answer here to be useful to someone else that doesn't know the ML.

Upvotes: 3

Related Questions