A. *_*lff 10 javascript jquery window.open
这是测试用例.
使用JavaScript:
$('.js').on('click', function () {
var newwindow = window.open();
newwindow.document.write('<span>test</span>');
newwindow.document.write('<scr' + 'ipt>alert(1)</scr' + 'ipt>');
});
Run Code Online (Sandbox Code Playgroud)
这给出了预期的结果:对话框警报显示在新窗口内.
使用jQuery:
$('.jquery').on('click', function () {
var newwindow = window.open();
$(newwindow.document.body).append('<span>test</span>', '<scr' + 'ipt>alert(1)</scr' + 'ipt>');
});
Run Code Online (Sandbox Code Playgroud)
对话框警报显示在主页面内.
为什么不同?我在这里错过了什么吗?
此行为已在chrome/FF/safari/IE中测试过
编辑
正如mishik所指出的,这是由于jQuery如何处理脚本标记,使用该globalEval方法在全局上下文中运行脚本.因此,使用jQuery的可能解决方法(但不能回归到纯JavaScript方法)可能是newwindow在全局上下文中设置变量并使用它,例如:
$('.jquery').on('click', function () {
newwindow = window.open();
$(newwindow.document.body).append('<span>test</span>','<scr' + 'ipt>newwindow.window.alert(1)</scr' + 'ipt>');
});
Run Code Online (Sandbox Code Playgroud)
似乎这是jQuery处理<script>标记的方式.
domManip 函数在jQuery源代码中:
// 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, "" ) );
}
}
}
Run Code Online (Sandbox Code Playgroud)
domManip将删除所有<script>元素,在全局上下文中评估它们然后禁用.
domManip通过append()方法调用:
append: function() {
return this.domManip( arguments, function( elem ) {
Run Code Online (Sandbox Code Playgroud)