This is the test case.
Using JavaScript:
$('.js').on('click', function () {
var newwindow = window.open();
newwindow.document.write('<span>test</span>');
newwindow.document.write('<scr' + 'ipt>alert(1)</scr' + 'ipt>');
});
This gives the expected result: the dialog alert is showing inside the new window.
Using jQuery:
$('.jquery').on('click', function () {
var newwindow = window.open();
$(newwindow.document.body).append('<span>test</span>', '<scr' + 'ipt>alert(1)</scr' + 'ipt>');
});
The dialog alert is shown inside the main page.
Why the difference? Am I missing something here?
This behaviour has been tested in chrome/FF/safari/IE
EDIT
As pointed out by mishik, this is due to how jQuery handles script tags, using the globalEval
method to run scripts in the global context. So a possible workaround for using jQuery (but not fall back to the pure JavaScript method) could be to set the newwindow
variable in the global context too and use it like that, e.g:
$('.jquery').on('click', function () {
newwindow = window.open();
$(newwindow.document.body).append('<span>test</span>','<scr' + 'ipt>newwindow.window.alert(1)</scr' + 'ipt>');
});
DEMO
The reason alert() does not work is because previously you have checked "prevent this page from creating additional dialoug" checkbox. lets take a look at this code. There will be two alert boxes if you run the code.
The Window alert() method is used to display an alert box.
JavaScript Alert: After Page Loads If you prefer to have the full page visible while the user reads the alert box message, use the onLoad event. To do this, place a function in the document's <head> , then trigger it using the onLoad attribute in the document's <body> tag.
To invoke an alert system dialog, you invoke the alert() method of the window object. alert(message); The message is a string that contains information that you want to show to users. When the alert() method is invoked, a system dialog shows the specified message to the user followed by a single OK button.
Seems like this is the way jQuery handles <script>
tag.
domManip
function in jQuery source code:
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
domManip
will strip all the <script>
elements, evaluate them in global context and then disable.
domManip
is called by append()
method:
append: function() {
return this.domManip( arguments, function( elem ) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With