I’m injecting Javascript into a page w/ Greasemonkey, doing some processing on the body content (adding markup) then re-inserting the content. The problem is that all the events in the original content are lost, breaking things like onClick events that were added when the page initially loaded.
My original idea was to do this (using jQuery) to just re-add the script tags to the head:
$('script').each(function(s, script) { $(script).appendTo('head'); })
or just:
$('script').appendTo('head');
I thought this would cause scripts to reload/reeval, but it doesn’t work.
A simple example of where I’d like to do this would be on: http://en.m.wikipedia.org/wiki/John_Hardy_%28song%29 I’d need to re-apply the this event found in application.js
$("h2.section_heading").click(function() {
// Do something
})
The question of whether and when browsers execute
<script>tags that are being added to the page by various methods is a thorny one, made if anything more complicated by jQuery’s attempts to work around the issue. You really don’t want to get into this.In any case, as Pointy says, there is no guarantee whatsoever that simply running the page’s scripts a second time will make them work with the new content. They may have all sorts of references to old (now replaced) nodes and may not expect to be entered a second time at all.
Don’t do processing on markup. HTML string hacking is massively unreliable quite apart from the problem of it replacing all the old objects when you write it back with
innerHTML. If you’re, say, adding'<span class="highlight">'to the HTML via regex hacks, you’ve just dug yourself a well of bugs, incompatibilities and potential XSS vulnerabilities.You’ve got a perfectly good DOM tree sitting in the browser. Do the processing on that, adding elements and setting attributes over the existing nodes! It’s easier, way more reliable, and for many operations much faster.