Shayan
Shayan

Reputation: 867

How to monitor a webpage for changes using Javascript?

I've searched for this a lot and for a long time, all I can find is online websites that will monitor websites for you but mostly require money to scan in short intervals. There might be software or browser extensions out there that also claim to do the job but I didn't have any success with them.

Since I'm learning JS, I thought there might be some way to do this myself.

Here's what I've thought of, comparing document.body before and after a change. So using Developer's Tools Console (F12), I tried this:

x=document.body
    <body style=​"background-color:​ rgb(21, 32, 43)​;​">​…​</body>​
r=document.createElement("p")
    <p>​</p>​
r.innerHTML="hi"
    "hi"
document.body.appendChild(r)
    <p>hi​</p>​
y=document.body
    <body style=​"background-color:​ rgb(21, 32, 43)​;​">​…​</body>​
x==y
    true

I don't understand why it reports "true", it should report false.

Why?

Any recommendation on how to get this done is very well appreciated.


new observation:

If x=document.body

then add a new <p></p> to body

and I do x=x.innerHTML

then do y=document.body.innerHTML

x==y will report true. (WHY?!)

BUT:

If x=document.body and I do x=x.innerHTML

then add a new <p></p> to body

then do y=document.body.innerHTML

x==y will report false.

Upvotes: 1

Views: 5800

Answers (1)

GammaGames
GammaGames

Reputation: 1828

When you are comparing x and y in the example code you are checking if the body is equal to the body, they are the same element so they would be equal.

You would want to set x to the textContent or innerHTML of the body, then compare it in the same way after modification.

You can alternatively use a mutation observer to listen for DOM changes as they happen, rather than at certain moments in time.

Upvotes: 3

Related Questions