Question

I am trying to develop a Firefox add-on using the documentation provided by the MDN. My regex works well when tested on a sample HTML page. But, the problem occurs when developing an add-on. Following is my code which is saved by the name my-scripts.js.

$("body:first").each(function(){
// Create a REGEX Expression to detetc a phone number
var regex =/\+\d{0,3}[-.\s]?\(?\d?\)?[-.\s]?\s?\d{1,4}[-.\s]?\d{1,9}[-.\s]?\d{5}/g;
var text = $(this).html();
text = text.replace(regex, "<a href=\"javascript:;\">$&</a>");
$("body:first").html(text);
});

Following is the main Javascript file called main.js.

var pageMod = require("sdk/page-mod");
var { MatchPattern } = require("sdk/util/match-pattern");
var pattern = new MatchPattern("http://example.com/*");
var self = require("sdk/self");
pageMod.PageMod({
contentScriptFile: [self.data.url("jquery-1.11.0.js"), self.data.url("my-script.js")]
});

My regex is perfect, but doesn't detect numbers on a given web page

Examples

+111111111111
+11 (1) 111 11 11111
+11 (1) 111 11-11111
+11 111 11 11111
+11 (1) 1111 111111111
+11111111111111
+11 1111 111111111
Was it helpful?

Solution

The (lower level) match pattern API is built into the (higher level) PageMod API in the form of the include property in the constructor. The only reason the match-pattern module is linked to in the PageMod docs is so that you have an idea of how the matching strings work.

So if want your add-on to be applied to "http://example.com/*", main.js should look like:

var {data} = require("sdk/self");
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "http://example.com/*",
  contentScriptFile: [data.url("jquery-1.11.0.js"), data.url("my-script.js")]
});

If I misinterpreted that (the match-pattern lines were in there for another reason), and you want your regex to be applied to every page, use include: '*'.

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