0

I am having trouble replacing the html of a webpage using a chrome extension. After a regex search and replace, I then want to replace the html of the body tag using jQuery. However, functionality on the page always breaks when I do this and I don't know why.

As an example, run this in your console on StackExchange. Once you have done so, you cannot click on the up and downvote buttons, even though all you are doing is replacing the body's html with itself.

$('body').html($('body').html());
user24984
  • 185
  • 1
  • 12
  • Okay, bad duplicate, still.. – Xan Sep 24 '15 at 22:01
  • the short answer for this site at least: the script tags don't get copied over when using jQuery (security concerns), you'd need to deal with that – Daemedeor Sep 24 '15 at 22:02
  • protip for click handlers and doing things in the console: look at the actual DOM and look at what the dom looks like after you do something..... then you'd see all the script tags dissappear – Daemedeor Sep 24 '15 at 22:04

1 Answers1

2
$('body').html($('body').html());

is functionally equivalent to:

var string = $('body').html();
$('body').html(string)

This conversion loses all information not present in that string.

This includes almost all event listeners and other JavaScript state information.

As such, you really, really should never do that. Instead, you need to carefully operate only on the content you need to change.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • i feel this is covered elsewhere in s.o. but didnt find it on a quick search. saw you also tried to mark as dup. – Zig Mandel Sep 25 '15 at 13:36