cordova组件

cordova常用组件及用法梳理

概述

config.xml

1
<plugin name="cordova-plugin-camera" spec="^4.0.3" />

表示当前安装的插件。

使用Cordova CLI 跨平台安装插件

可在官网查询组件

事件触发必须在deviceready事件之后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var app = {

initialize: function () {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},

onDeviceReady: function () {
this.receivedEvent('deviceready');
},

receivedEvent: function (id) {

var _this = this;

// 绑定事件
document.getElementById("alertDialog").addEventListener("click", _this.alertDialog);
},

// 函数
alertDialog() {
navigator.notification.alert('消息', () => {
console.log('alert')
}, '标题', '确认')
}
}

app.initialize();

相机

安装

1
cordova plugin add cordova-plugin-camera

示例

html:

1
2
3
<button id = "cameraTakePicture">照相机</button>
<img id = "myImage"></img>
<button id = "cameraGetPicture">相册</button>

拍照功能:

添加事件监听器:

1
document.getElementById("cameraTakePicture").addEventListener("click", cameraTakePicture);

调用由插件API提供的 navigator.camera全局对象。拍摄成功回调函数onSuccess

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function cameraTakePicture() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});

function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
console.log(imageData);
}

function onFail(message) {
alert('Failed because: ' + message);
}
}

相册功能:

添加事件监听器:

1
document.getElementById("cameraGetPicture").addEventListener("click", cameraGetPicture);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function cameraGetPicture() {
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
});

function onSuccess(imageURL) {
var image = document.getElementById('myImage');
image.src = imageURL;
}

function onFail(message) {
alert('Failed because: ' + message);
}
}

主要参数

参数 描述
quality 图像质量在0-100范围内。 默认值为50。
destinationType DATA_URL 或 0 返回base64编码字符串。

FILE_URI 或 1 返回图片文件URI。

NATIVE_URI 或 2 返回图片本机URI。 |
| sourceType | PHOTOLIBRARY 或 0 打开照片库。

CAMERA 或 1 打开本机相机。

SAVEDPHOTOALBUM 或 2 打开已保存的相册。 |
| mediaType | PICTURE 或 0 仅允许选择图片。

VIDEO 或 1 仅允许视频选择。

ALLMEDIA 或 2 允许选择所有媒体类型。 |

文件系统

安装

1
cordova plugin add cordova-plugin-file

示例

html:

1
2
3
4
<button id = "createFile">创建文件</button>
<button id = "writeFile">写文件</button>
<button id = "readFile">读文件</button>
<button id = "removeFile">删除文件</button>

添加事件监听器:

1
2
3
4
document.getElementById("createFile").addEventListener("click", createFile);
document.getElementById("writeFile").addEventListener("click", writeFile);
document.getElementById("readFile").addEventListener("click", readFile);
document.getElementById("removeFile").addEventListener("click", removeFile);

创建文件

设备上的应用程序根文件夹中创建文件。window.requestFileSystem请求文件系统,类型可以是 WINDOW.TEMPORARY 或 WINDOW.PERSISTENT,size是存储所需的字节值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function createFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;

window.requestFileSystem(type, size, successCallback, errorCallback)

function successCallback(fs) {
fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
alert('File creation successfull!')
console.log(fileEntry);
}, errorCallback);
}

function errorCallback(error) {
alert("ERROR: " + error.code)
}
}

写文件

请求文件系统,然后创建文件写入器,写入我们分配给 blob 变量的文本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function writeFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;

window.requestFileSystem(type, size, successCallback, errorCallback)

function successCallback(fs) {
fs.root.getFile('log.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
alert('Write completed.');
console.log(e);
};

fileWriter.onerror = function(e) {
alert('Write failed: ' + e.toString());
};

var blob = new Blob(['test text'], {type: 'text/plain'});
fileWriter.write(blob);
}, errorCallback);
}, errorCallback);
}

function errorCallback(error) {
alert("ERROR: " + error.code)
}
}

读取文件

请求文件系统并获取文件对象,创建 reader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function readFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;

window.requestFileSystem(type, size, successCallback, errorCallback)

function successCallback(fs) {
fs.root.getFile('log.txt', {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log(e);
};
reader.readAsText(file);
console.log(file);
}, errorCallback);
}, errorCallback);
}

function errorCallback(error) {
alert("ERROR: " + error.code)
}
}

删除文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function removeFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;

window.requestFileSystem(type, size, successCallback, errorCallback)

function successCallback(fs) {
fs.root.getFile('log.txt', {create: false}, function(fileEntry) {
fileEntry.remove(function() {
alert('File removed.');
}, errorCallback);
}, errorCallback);
}

function errorCallback(error) {
alert("ERROR: " + error.code)
}
}

复制文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function copyFile() {
window.resolveLocalFileSystemURL(
'file:///storage/emulated/0/Pictures/1554715930793.jpg',
function (fileEntry) {
window.resolveLocalFileSystemURL(
'file:///storage/emulated/0/Sounds/',
function (dirEntry) {
fileEntry.copyTo(dirEntry, 'new.jpg', () => {
console.log('文件复制成功');
}, () => {
console.log('文件复制失败');
});
},
function (error) {
console.log('创建失败1!');
}
);
},
function (error) {
console.log('创建失败2!');
}
);
}

上传下载文件

安装

1
cordova plugin add cordova-plugin-file-transfer

示例

html:

1
2
<button id = "uploadFile">上传</button>
<button id = "downloadFile">下载</button>

事件监听器:

1
2
document.getElementById("uploadFile").addEventListener("click", uploadFile);
document.getElementById("downloadFile").addEventListener("click", downloadFile);

下载

从服务器下载文件到设备。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function downloadFile() {

var fileTransfer = new FileTransfer();
var uri = encodeURI("https://cn.vuejs.org/images/logo.png"); // 服务器下载链接
var fileURL = "///storage/emulated/0/DCIM/myFile"; // 设备上DCIM文件夹的路径

fileTransfer.download(
uri, fileURL, function(entry) {
console.log("download complete: " + entry.toURL());
console.log(entry);
},

function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
},

false, // not trustAllHosts
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}

上传

将文件上传到服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function uploadFile() {
var fileURL = "///storage/emulated/0/DCIM/myFile"
var uri = encodeURI("http://posttestserver.com/post.PHP");
var options = new FileUploadOptions();

options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType = "text/plain";

var headers = {'headerParam':'headerValue'};
options.headers = headers;

var ft = new FileTransfer();

ft.upload(fileURL, uri, onSuccess, onError, options);

function onSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
console.log(r);
}

function onError(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}

地理位置

安装

1
cordova plugin add cordova-plugin-geolocation

示例

html:

1
<button id = "getPosition">当前位置</button>

事件监听器:

1
document.getElementById("getPosition").addEventListener("click", getPosition);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function getPosition() {

var options = {
enableHighAccuracy: true, // 如果请求没有按时完成,我们将使用最后一个已知的值
maximumAge: 3600000 // 最大缓存
}

var watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, options);

function onSuccess(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
console.log(position);
};

function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
}

音频

安装

1
cordova plugin add cordova-plugin-media

示例

html:

1
2
3
4
5
<button id = "playAudio">播放</button>
<button id = "pauseAudio">暂停</button>
<button id = "stopAudio">停止</button>
<button id = "volumeUp">音量+</button>
<button id = "volumeDown">音量-</button>

事件监听器:

1
2
3
4
5
document.getElementById("playAudio").addEventListener("click", playAudio);
document.getElementById("pauseAudio").addEventListener("click", pauseAudio);
document.getElementById("stopAudio").addEventListener("click", stopAudio);
document.getElementById("volumeUp").addEventListener("click", volumeUp);
document.getElementById("volumeDown").addEventListener("click", volumeDown);

播放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var myMedia = null;

function playAudio() {
var src = "/android_asset/www/audio/piano.mp3";

if(myMedia === null) {
myMedia = new Media(src, onSuccess, onError);

function onSuccess() {
console.log("playAudio Success");
}

function onError(error) {
console.log("playAudio Error: " + error.code);
}

}
myMedia.setVolume(0.5);
myMedia.play();
}

暂停和停止

1
2
3
4
5
6
7
8
9
10
11
12
function pauseAudio() {
if(myMedia) {
myMedia.pause();
}
}

function stopAudio() {
if(myMedia) {
myMedia.stop();
}
myMedia = null;
}

音量控制

setVolume 方法。此方法采用参数,其值从 01 。将设置起始值为 0.5

1
2
3
4
5
6
7
8
9
10
11
12
13
var volumeValue = 0.5;

function volumeUp() {
if(myMedia && volumeValue < 1) {
myMedia.setVolume(volumeValue += 0.1);
}
}

function volumeDown() {
if(myMedia && volumeValue > 0) {
myMedia.setVolume(volumeValue -= 0.1);
}
}

其他方法

方法 描述
getDuration 返回音频的持续时间
startRecord 开始录制音频文件
stopRecord 停止录制音频文件

媒体捕获

安装

1
cordova plugin add cordova-plugin-media-capture

示例

html:

1
2
3
<button id = "audioCapture">录音</button>
<button id = "imageCapture">拍照</button>
<button id = "videoCapture">摄像</button>

事件监听器:

1
2
3
document.getElementById("audioCapture").addEventListener("click", audioCapture);
document.getElementById("imageCapture").addEventListener("click", imageCapture);
document.getElementById("videoCapture").addEventListener("click", videoCapture);

录音

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function audioCapture() {

var options = {
limit: 1, // 每次只录制一个
duration: 10 // 音片段的秒数
};

navigator.device.capture.captureAudio(onSuccess, onError, options);

function onSuccess(mediaFiles) {
var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
console.log(mediaFiles);
}
}

function onError(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
}
}

拍照

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function imageCapture() {

var options = {
limit: 1
};

navigator.device.capture.captureImage(onSuccess, onError, options);

function onSuccess(mediaFiles) {
var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
console.log(mediaFiles);
}
}

function onError(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
}
}

摄像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function videoCapture() {

var options = {
limit: 1,
duration: 10
};

navigator.device.capture.captureVideo(onSuccess, onError, options);

function onSuccess(mediaFiles) {
var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
console.log(mediaFiles);
}
}

function onError(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
}

}

白名单

创建新的Cordova项目时,默认情况下会安装并实施白名单插件。

导航白名单。允许链接到一些外部URL。config.xml 中配置

1
<allow-navigation href = "http://example.com/*" />

Intent Whitelist

意向白名单。用于指定允许打开系统的URL。 config.xml 中看到Cordova已经允许我们使用大部分所需的链接。

1
2
3
4
5
6
7
8
9
10
11
12
13
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>

Network Request Whitelist

网络请求白名单。

config.xml 文件中,有< Access origin ="\*"/>元素。此元素允许对应用程序的所有网络请求。如果只想允许特定请求,可以自行设置

1
<access origin="*" />
1
<access origin = "http://example.com" />

Content Security Policy

内容安全策略。位于 index.HTML 中的 head 元素中。

默认:

1
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">

允许来自同源和 foo.com的所有内容:

1
<meta http-equiv = "Content-Security-Policy" content = "default-src 'self' foo.com">

允许所有内容,但将CSSjavascript限制同源:

1
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

获取当前应用版本号

安装

1
cordova plugin add cordova-plugin-app-version

示例

1
2
3
cordova.getAppVersion.getVersionNumber(function (version) {
alert(version);
});
方法 含义
getAppName app名
getPackageName 包名
getVersionCode app版本码
getVersionNumber app版本号

网络信息

安装

1
cordova plugin add cordova-plugin-network-information

示例

通过navigator.connection.type获取网络类型,取值如下:

常量 含义
Connection.UNKNOWN 未知
Connection.ETHERNET 以太网
Connection.WIFI wifi
Connection.CELL_2G 2G蜂窝
Connection.CELL_3G 3G蜂窝
Connection.CELL_4G 4G蜂窝
Connection.CELL 蜂窝
Connection.NONE 无网络

另有offline事件和online事件。

1
document.addEventListener("offline", yourCallbackFunction, false);
1
document.addEventListener("online", yourCallbackFunction, false);

弹窗

提供四种原生弹窗样式。

安装

1
cordova plugin add cordova-plugin-dialogs
1
navigator.notification.alert(message, alertCallback, [title], [buttonName])

message为弹窗消息,

alertCallback为弹窗消失后的回调函数,

title为弹窗标题,默认为Alert

buttonName为按钮名,默认为OK

1
navigator.notification.alert(message, confirmCallback, [title], [buttonLabels])

message为弹窗消息,

confirmCallback为弹窗消失后的回调函数,参数为点击的按钮index,例如1,2,直接关闭参数为0

title为弹窗标题,默认为Confirm

buttonLabels为按钮标签数组,默认为[OK,Cancel]

1
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])

发出蜂鸣声

1
navigator.notification.beep(times);

设备信息

安装

1
cordova plugin add cordova-plugin-device

API

参数 含义
device.cordova Cordova版本
device.model 设备型号
device.platform 平台
device.uuid UUID
device.version 设备版本

首屏加载

安装

1
cordova plugin add cordova-plugin-splashscreen

示例

config.xml中会出现如下:

1
2
3
4
5
6
7
8
9
<splash src="res/screen/ios/Default~iphone.png" width="320" height="480"/>
<splash src="res/screen/ios/Default@2x~iphone.png" width="640" height="960"/>
<splash src="res/screen/ios/Default-Portrait~ipad.png" width="768" height="1024"/>
<splash src="res/screen/ios/Default-Portrait@2x~ipad.png" width="1536" height="2048"/>
<splash src="res/screen/ios/Default-Landscape~ipad.png" width="1024" height="768"/>
<splash src="res/screen/ios/Default-Landscape@2x~ipad.png" width="2048" height="1536"/>
<splash src="res/screen/ios/Default-568h@2x~iphone.png" width="640" height="1136"/>
<splash src="res/screen/ios/Default-667h.png" width="750" height="1334"/>
<splash src="res/screen/ios/Default-736h.png" width="1242" height="2208"/>

这些是默认的首屏加载图,分别对应不同的屏幕大小。可以任意替换这些资源。

屏幕方向

安装

1
cordova plugin add cordova-plugin-screen-orientation

示例

1
2
3
4
5
6
7
8
// 锁定方向
screen.orientation.lock('portrait');

// 解锁方向
screen.orientation.unlock();

// 获取当前方向
screen.orientation.type;

API

含义
default 默认
landscape 横屏
portait 竖屏

退出应用

安装

1
cordova plugin add cordova-plugin-exitapp

示例

1
navigator.app.exitApp();

状态栏

安装

1
cordova plugin add cordova-plugin-statusbar

用法

config.xml中进行配置

1
<preference name="StatusBarOverlaysWebView" value="true" />

在启动时是否使状态栏覆盖WebView

1
<preference name="StatusBarBackgroundColor" value="#000000" />

背景色

1
<preference name="StatusBarStyle" value="lightcontent" />

样式,可选default, lightcontent, blacktranslucent, blackopaque

1
<preference name="StatusBarDefaultScrollToTop" value="false" />

是否让Cordova WebView获取默认的scroll-to-top行为

其他插件

插件 描述
cordova-plugin-battery-status 电池状态
cordova-plugin-contacts 联系人