var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeSript({file: "myscript.js"});
});
经过测试(测试环境为小米3手机),以上代码并不能正确执行,后来调用完整代码可顺利加载,代码如下:
var iabRef = null;
// Inject our custom JavaScript into the InAppBrowser window
//
function replaceHeaderImage() {
iabRef.executeScript({
code: "var img=document.querySelector('#header img'); img.src='http://cordova.apache.org/images/cordova_bot.png';"
}, function() {
alert("Image Element Successfully Hijacked");
});
}
function iabClose(event) {
iabRef.removeEventListener('loadstop', replaceHeaderImage);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
//
function onDeviceReady() {
iabRef = window.open('http://apache.org', '_blank', 'location=yes');
iabRef.addEventListener('loadstop', replaceHeaderImage);
iabRef.addEventListener('exit', iabClose);
}
所以我怀疑executeScript方法需要放在loadstop事件中才能起作用。
再有就是executeScript里面可以运行code,也可以加载js文件,如果加载文件的话代码如下:
iabRef.executeScript({
file: "aaa.js"
}, function() {
});
经测试,如果window.open是访问app内部的html页面,则加载成功,但如果是外部网页,则加载失败,也就是window.open中的一个参数是http开头的网址就无法加载js文件,具体原因不详。最后通过另一种方法解决,代码如下:
var jqstr=null;
$.ajax({
url: 'aaa.js',
dataType: "script",
cache:true,
success: function(data){
jqstr=data;
}
});
function replaceHeaderImage() {
iabRef.executeScript({
code: jqstr
}, function() {
alert("Image Element Successfully Hijacked");
});
}
function iabClose(event) {
iabRef.removeEventListener('loadstop', replaceHeaderImage);
iabRef.removeEventListener('exit', iabClose);
}
// device APIs are available
//
function onDeviceReady() {
iabRef = window.open('http://apache.org', '_blank', 'location=yes');
iabRef.addEventListener('loadstop', replaceHeaderImage);
iabRef.addEventListener('exit', iabClose);
}
也就是先通过ajax把js文件中的代码抓出来,付给一个变量,再通过code的方式加载,则可顺利加载