0

I am having an issue whereby I create a RegExp object in a content script and pass it as part of an object back to the main script using self.port.emit(). Somewhere along the way it seems to lose its identity as a RegExp and also its toString abilities. The following returns false in the main script, but true in the content script:

Object.prototype.toString.call(regexp) == '[object RegExp]';
regexp instanceof RegExp;

Interestingly for Arrays passed in the same way the following is true:

Object.prototype.toString.call(array) == '[object Array]'; 

Am I missing something?

2
  • 1
    At least in Chrome, trying to covert an expression to JSON results in an empty object: {foo: /test/} becomes "{"foo":{}}". JSON does not know regex types. I assume the same is happening in your case. Commented Aug 20, 2012 at 10:01
  • Sounds plausible, is annoying though! Commented Aug 20, 2012 at 12:31

2 Answers 2

1

The Add-on SDK doesn't pass objects around when you send messages, only strings - it essentially calls JSON.stringify() on one side and then JSON.parse() on the other. The result is easy to predict:

console.log(JSON.stringify(new RegExp()));

This gives you "{}". In other words, JSON.stringify() treats "custom" objects as normal objects without any properties, object prototypes and such are ignored. What you get in your main code is a plain object, same as if you call new Object().

If you need to pass a regular expression to your main code - send regexp.source, create an actual regular expression on the other side. Sending actual objects around isn't possible.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, are you sure about "JSON.stringify() treats "custom" objects as normal objects without any properties" though? Any custom defined fields seem to be preserved.
@Arth: Well, custom properties are preserved - but regexp-specific ones (meaning: defined on the prototype) aren't.
1

What about if you just sent the regex pattern instead of the whole rexexp object? e.g. encodeURIComponent(regexp.source);

1 Comment

I didn't want to target the regexp specifically because the JSON object gets recursively turned into a custom script at the other end and includes strings and Arrays. I think I prefer JSON.stringify() to URI encoding, but this is basically what I have done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.