views:

36

answers:

1

I've been working on Chrome Extension for a website for the past couple of days. It's coming along really nicely but I've encountered a problem that you might be able to help with.

Here's an outline of what the extension does (this functionality is complete):

  1. A user can enter their username and password into the extensions popup - and verify their user account for the particular website
  2. When a user browses http://twitter.com a content script is dynamically included that manipulates the DOM to include an extra button next to each tweet displayed.
  3. When a user clicks this button they are presented with a dialog box

I've made a lot of progress but here is my problem:

When a user visits Twitter the content script is activated and all tweets on the page get my new button - but if the user then clicks 'More...' and dynamically loads the next 20 tweets... these new additions to the page DOM do not get affected by the content script (because it is already loaded).

I could add an event listener to the 'More...' button so it then triggers the original content script again (and adds the new button) but i would have to predict the length of twitter's ajax request response. I can't tap into their Ajax request that pulls in more tweets and call my addCurateButton() function once the request is complete.

What do you think is the best solution? (if there is one)

A: 

Interacting with Ajax is probably the hardest thing to coax a content script to do, but I think you’re on the right track. There are a couple different approaches I’ve taken to solving this problem. In your case, though, I think a combination of the two approaches (which I’ll explain last) would be best.

  1. Attach event listeners to the DOM to detect relevant changes. This solution is what you’ve suggested and introduces the race condition.

  2. Continuously inspect the DOM for changes from inside a loop (preferably one executed with setInterval). This solution would be effective, but relatively inefficient.

The best-of-both-worlds approach would be to initiate the inspection loop only after the more button is pressed. This solution would both avoid the timing issue and be efficient.

byoogle