1

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?

3
  • is the new window opened using the same URL as the main window? eg.: both are ponted to yoursite.com... Commented Feb 15, 2015 at 20:13
  • What do you mean by new opened window,? Commented Feb 15, 2015 at 20:14
  • The new window is obviously in the same domain, otherwise I couldn't insert new html inside it (which does work, btw. only scripts does not get executed). Actually it could be an "about:blank" page. I use window.open() function. Commented Feb 15, 2015 at 21:08

2 Answers 2

3

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>");
Sign up to request clarification or add additional context in comments.

2 Comments

and I do something very similar and it does not working. I think I get the problem. It seems that jQuery runs the script but in the context of the wrong window, i.e, it the context of the parent window instead of the new window - where the script is actually inserted.
If you import jquery in the opened page as well you may call: popup.$() instead. It will call jQuery instance in the opened window
0

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.

1 Comment

The issue is this, the content I get from the ajax response is already in use in the current window (and working). I'm trying to add an option in my site to view the same content in a new window.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.