user3599803
user3599803

Reputation: 7034

insert script to new window with jquery html()

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

Answers (2)

nanndoj
nanndoj

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

Lelio Faieta
Lelio Faieta

Reputation: 6684

I use to do in a different way. Ajax returns a page with $(document).readyand 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

Related Questions