[英]deviceready not firing in Cordova app on iOS
我有index.html,其中將deviceready
事件偵聽器添加到了腳本標簽。 但這不是在加載HTML時觸發的。 相反,點擊主頁按鈕當從觸發onAppDidEnterBackground
的方法CDVViewController
。
我想調用我的自定義插件來獲取要在加載的HTML中填充的值。 我發現很少有解決方案要求更改meta標簽。 我確實嘗試過更改,但沒有用。 它在iOS9中也不起作用。 我猜元標記問題來自iOS10。 我不確定我在這里缺少什么。
科爾多瓦v4.4.0
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: http://* 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title>My HTML Document</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src='cordova.js'></script>
<script type="text/javascript" src='CustomPlugin.js'></script>
<script>
document.addEventListener('deviceready', function () {
window.plugins.CustomPlugin.myMethod(function (result) {
document.getElementById('Name').value = result['Name'];
}, function (error) {
alert(error);
});
}, false);
</script>
</head>
<body>
<div class='article'>
<div class='tableWrapper'>
<table>
<tr>
<td class='right'>CName:</td>
<td colspan='3'><input type='text' id='Name'/></td>
</tr>
</table>
</div>
</div>
</body>
</html>
如果您遇到的問題與我相同,那么這與您的內容安全策略元標記有關。 我使用了以下答案中的一個,問題得以解決。
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data:* gap://* tel:* 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'" />
嘗試將addEventListener放入函數onLoad中,並在body標簽中使用onload事件調用它:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
//the code you want to execute
}
和
<body onload="onLoad()">
因為如果您按照自己的方式進行操作,那么您將嘗試在加載cordova庫之前執行deviceready事件。
將所有腳本加載到html主體的底部
<html lang="en">
<head>...</head>
<body>
<div>Your content here</div>
...
<script type="text/javascript" src='CustomPlugin.js'></script>
<script type="text/javascript" src='cordova.js'></script>
<script type="text/javascript" src='main.js'></script>
</body>
</html>
並創建main.js文件,然后將代碼放入其中。
window.onload = function(){
document.addEventListener("deviceready", firstInitCordova, true);
};
function firstInitCordova(){
if(!window.cordova){
// If cordova is not defined then call this function again after 2 second
setTimeout(firstInitCordova, 2000);
return;
}
//console.log(window.plugins);
window.plugins.CustomPlugin.myMethod(function (result) {
document.getElementById('Name').value = result['Name'];
}, function (error) {
alert(error);
});
}
// If you're unsure then set a timer
setTimeout(function(){
firstInitCordova();
}, 3000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.