如何在cordova/phonegap应用程序中截取屏幕截图

Boy*_*tov 4 javascript android angularjs cordova cordova-plugins

我试图使用插件在我的cordova应用程序中截取屏幕截图,但是发生了错误.我真的不知道错误是什么,因为我在我的Android智能手机和应用程序上测试它只是块.在浏览器中,出现此错误的情况也是如此:TypeError: Cannot read property 'save' of undefined其中"save"来自此代码:

navigator.screenshot.save(function(error,res){
      if(error){
        console.error(error);
      }else{
        console.log('ok',res.filePath);
      }
    });
Run Code Online (Sandbox Code Playgroud)

PS:也试过navigator.plugin.screenshot...,navigator.plugins.screenshot,          window.screenshot,window.plugin.screenshotwindow.plugins.screenshot

PS2:我检查了插件是否安装cordova plugins在cordova CLI中,一切正常,插件存在于plugins文件夹中,适用于cordova版本> = 3.0.0而且我的是更新版本

但是当然,浏览器并没有真正加载插件,因为这个错误也出现在那里:Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:23273/www/cordova_plugins.json.没有截图,在我的智能手机上查看.

Tal*_*tro 6

我正在使用Worklight并且遇到了同样的问题.我的解决方案是将Screenshot.js文件的代码更改为:

var formats = ['png','jpg'];

function Screenshot() {
}

Screenshot.prototype.save = function (callback,format,quality, filename) {
    format = (format || 'png').toLowerCase();
    filename = filename || 'screenshot_'+Math.round((+(new Date()) + Math.random()));
    if(formats.indexOf(format) === -1){
        return callback && callback(new Error('invalid format '+format));
    }
    quality = typeof(quality) !== 'number'?100:quality;
    cordova.exec(function(res){
        callback && callback(null,res);
    }, function(error){
        callback && callback(error);
    }, "Screenshot", "saveScreenshot", [format, quality, filename]);
};

Screenshot.install = function () {
      if (!window.plugins) {
        window.plugins = {};
      }

      window.plugins.screenshot = new Screenshot();
      return window.plugins.screenshot;
    };

cordova.addConstructor(Screenshot.install); 
Run Code Online (Sandbox Code Playgroud)

这样我就可以使用以下代码进行调用:

window.plugins.screenshot.save(function(error,res){
          if(error){
            alert(error);
          }else{
            alert('ok',res.filePath); //should be path/to/myScreenshot.jpg
          }
        },'jpg',50,'myScreenShot');
Run Code Online (Sandbox Code Playgroud)

这完全适用于我的Android智能手机.

我还在res/xml/config.xml文件中添加了:

<feature name="Screenshot">
    <param name="android-package" value="org.apache.cordova.screenshot.Screenshot"/>
</feature>
Run Code Online (Sandbox Code Playgroud)

在AndroidManifest.xml文件中:

<uses-permission android: name = "android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

并在以下包中添加了java类:org.apache.cordova.screenshot.Screenshot

所有这些配置都包含插件的plugin.xml文件中的信息