How can I track changes in content on an HTML page

2020-07-27 04:28发布

问题:

I'm wracking my brain on this one.

After an HTML document loads in a browser, I want to be able to monitor the page in case any content on it changes for any reason.

Is there a Javascript function with which I can track 'what has changed' on the webpage. This should be irrespective of the type of content on the HTML page.

I have two examples for you to ponder on:

Ex1:

Say in an HTML document there are two select boxes s1 and s2. The items list in s2 depends on selections in s1 (page is not refreshed — that is, s2 is loaded through Ajax or something). So after the HTML page loads I need to get a notification whenever s2 is populated...

Ex2:

Say, in an HTML page, there's a link, Onclicking which a light pop-up div is created with some text. How can I capture the content of this dynamic pop-up?

In all this discussion, I'm not taking into account any particular format of HTML...the HTML content can be anything...I just need to keep tracking if any content changes after the page loads...

Ideally I need to achieve this using JavaScript (client-side scripting). How can I achieve this?

回答1:

You can keep track of changes in a textbox using onkeyup. This will tell you every time someone makes a change in a given textbox.

This could potentially fire alot of events. However, using onblur won't necessarily tell you about changes in the textbox and onchange's browser coverage is spotty at best.



回答2:

If you are using AJAX, you could setup the response function to handle a home grown "event listening" system. So after the response does what it needs to do, it could call any methods that were registered with it, passing in the response text when necessary.

So from your examples above, in Ex1, when the AJAX returns from S1, it would load S2, then call a method saying S2 had changed. In Ex2, when the new AJAX returns the DIV's contents, after loading it into the DIV, it call a different method (or possibly the same depending on what your trying to do) and alerts it that the DIV has new contents.



回答3:

You could set your "watcher" script as a timer, running a diff function on the current document.body.innerHTML and a stored version captured on load. Depending on how fast the diff will run will give you an idea on what timer interval to use.

This may not capture changes in form elements, but for those, it's easier to loop through all form elements in every form on the page.

Here's someone's diff function I found on Google: http://snowtide.com/jsdifflib



标签: html ajax