【发布时间】:2014-04-03 10:45:21
【问题描述】:
我正在编写一个虚拟应用程序来测试 Cordova 的 InAppBrowser 插件中的 executeScript() 方法是如何工作的。特别是,我试图在一个 webview 中注入一个 javascript 代码。
这是我的 index.html 文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title>InAppBrowser Injection Test</title>
</head>
<body>
<div class="app">
<h1>Testing Injection</h1>
<div id="deviceready" class="blink">
<p class="event listening">Starting Mother WebView</p>
<div class="event received">
<p>Device is Ready</p>
</div>
</div>
</div>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
还有 index.js 文件
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
var ref = window.open('http://www.example.net', '_blank', 'location=yes ,toolbar=yes, EnableViewPortScale=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() {
//ref.executeScript({ code: "alert('Injected Code')" });
ref.executeScript({ file: "externaljavascriptfile.js" });
showalert();
});
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
最后是 externaljavascriptfile.js
alert('External Injected Code');
如果我尝试直接注入 javascript 代码(即取消注释 "ref.executeScript({ code: "alert('Injected Code')" });" 行)一切正常,并且在页面加载后触发警报,但是如果我尝试注入外部 javascript(即使用“ref.executeScript({ file: "externaljavascriptfile.js" });”行,则不会发生任何事情。
我错过了什么吗?
【问题讨论】:
-
谢谢你的回答,但你也错过了重点。您链接的讨论是关于通过本机应用程序注入 javascript,这基本上是一个 Java 程序。我需要做同样的事情,但要通过 Phonegap/cordova。
标签: javascript cordova inappbrowser