Reputation: 7034
I usually insert html+scripts returned from ajax request to the document using jQuery html() method, which also executes the scripts.
Means that if I write:
$(document.body).html("<script>alert()</"+"script>");
it will execute the script.
(the + is only for the browesr, since writing </script>
in a string does not work.)
The problem - if I do the same for a new opened window, it does not work. i.e. the scripts are not executed. why?
Upvotes: 1
Views: 4409
Reputation: 6770
You can execute any script on the opened window if the target page and the main page are hosted in the same URL and protocol. (I assume it was opened using Window.open() function)
Save the reference to the opened window...
var popup = window.open("/page2.html");
and use it to access its document:
$(popup.document.body).append("<script>alert()</script>");
If you are importing jQuery in the opened window as well you can also call
popup.$(popup.document.body).append("<script>alert()</script>");
Upvotes: 3
Reputation: 6684
I use to do in a different way. Ajax returns a page with $(document).ready
and all the related code inside.
Then I load the piece of code returned from AJAX inside the ajax function with .html(data)
and jquery code always works.
If I am not wrong your issue is related to DOM is not ready in the new window.
Upvotes: 0