Jumpei Ogawa
Jumpei Ogawa

Reputation: 503

How to use page-mod to modify element loaded by JavaScript

I'm creating firefox addon to add onclick event to the specific button. ("input" element)

The button is placed in http://example.com/welcome#_pg=compose but when I open the page, following error occures:

TypeError: document.querySelector("#send_top") is null

#send_top is id of the button which I want to modify. So, the button is not found.

This error occurs because http://example.com/welcome and http://example.com/welcome#_pg=compose is completely different pages. In this case, the addon seems loading http://example.com/welcome but there is no button whose '#send_top' ID. When #_pg=compose anchor is added, the button is loaded by JavaScript.

How can I load http://example.com/welcome#_pg=compose to modify the button?

Upvotes: 1

Views: 481

Answers (1)

therealjeffg
therealjeffg

Reputation: 5830

Three thoughts to help you debug this:

  1. to correctly match the url you should consider using a regular expression instead of the page-match syntax - this might allow you to react to the anchors in a more predictable way

  2. I've found that when using content scripts with pages that are heavily modified by JS, you can run into timing issues. A hacky workaround might be to look for the element you want and, if it isn' there, do a setTimeout for a 100 milliseconds or so and then re-check. Ugly, yes, but it worked for some example code I used with the new twitter UI, for example.

  3. You can use the unsafeWindow variable in your content script to directly access the page's window object - this object will contain any changes JS has made to the page and is not proxied. You should use unsafeWindow with great caution however as its use represent a possible security problem. In particular, you should never trust any data coming from unsafeWindow, ever.

Upvotes: 2

Related Questions