Cannot use serialBluetooth functions even tough the plugin was installed - cordova-plugins

I cannot use the bluetoothSerial functions even though I installed the plugin by running cordova "plugin add cordova-plugin-bluetooth-serial" command in the project folder. I have received no errors and the plugin exists in the plugins folder.
I have tried adding plugin tag to the config.xml,
I have tried adding bluetooth permission to the AndroidManifest.xml
but none helped.
My cordova version is 9.0.0 (cordova-lib#9.0.1)
var app = {
initialize: function()
{
this.bindEvents();
},
bindEvents: function ()
{
document.addEventListener('deviceready',this.onDeviceReady(),
false)},
onDeviceReady: function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('touchstart', function(event){
console.log(event.touches);
touchX = event.touches[0].pageX;
touchY = event.touches[0].pageY;
console.log(touchX, touchY);
if (touchX <= button1.x + button1.width && touchX >= button1.x)
{
if (touchY <= button1.y + button1.height && touchY >=
button1.y) {
check = 1; // Everything is fine until here.
bluetoothSerial.isEnabled(success(), fail()); // the code
here and below here is never executed.
c.font = "80px Arial";
c.fillText("here",50,50);
}
}
When I debug using chrome://inspect/#devices I receive:
serialBluetooth is not defined error.
why is that happening?

It turned out that it is necessary to include the script tag, cordova.js.

Related

SELECT statement no longer working after installing cordova-plugin-ionic-webview

I was trying to fix some performance issues in my ionic hybrid app when using AWS cognito which requires installing cordova-plugin-ionic-webview. However, after installing this plugin, my SELECT statement is no longer working - it is now returning no records found. Here is the statement:
dbAccess.SelectGoodsReceiptDetail = function SelectGoodsReceiptDetail(goodsreceipt) {
var resultData = {};
// Select Multiple Items
return $q(function(resolve, reject) {db.executeSql("SELECT * FROM goodsreceiptdetailview WHERE goodsReceiptKey LIKE ?", [ goodsreceipt.header.goodsReceiptKey] , function(rs) {
resultData.data = [{}];
if (rs.rows.length > 0) {
if (rs.rows.item) {
for (i=0;i<rs.rows.length; i++) {
resultData.data[i] = rs.rows.item(i);
}
resultData.exist = true;
}
} else {
// no item found
resultData.exist = false;
}
resolve(resultData);
}, function(error) {
resultData.data = [{}];
resultData.exist = false;
resultData.failed = true;
resolve(resultData);
})
});
}
The variable goodsreceipt.header.goodsReceiptKey in an integer. I have read in the release notes for the cordova sqlite plugin that whole numbers are treated as REAL values when using WKWebView while it is being treated as INT on UIWebView here. Could this be causing the problem? How can I fix this with WKWebView?
I was able to fix this by converting the INT to string.

Cordova: Invalid data, chunk must be a string or buffer, not object

I updated to Ionic 3.5, and after that I get this error, when i try to do cordova build ios:
Invalid data, chunk must be a string or buffer, not object
There is no explanation of why this error is happening. I tried this both with Cordova 7.0.1 and 6.5.0. Interestingly, it works on Windows machine, but not on Mac. I only get the error on Mac. I appreciate any insights or helps.
ionic info
global packages:
#ionic/cli-utils : 1.5.0
Cordova CLI : 7.0.1
Ionic CLI : 3.5.0
local packages:
#ionic/app-scripts : 1.3.7
#ionic/cli-plugin-cordova : 1.4.1
#ionic/cli-plugin-ionic-angular : 1.3.2
Cordova Platforms : android 6.2.3
Ionic Framework : ionic-angular 3.5.3
System:
Node : v7.10.0
OS : Windows 10
Xcode : not installed
ios-deploy : not installed
ios-sim : not installed
npm : 4.6.1
I got the fix from one of the github issue. It just needed correct path for strings.xml.
There is no need to downgrade cordova or cordova-android
The fix is to replace the code in
/cordova-plugin-fcm/scripts/fcm_config_files_process.js as below:
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
fs.ensureDirSync = function (dir) {
if (!fs.existsSync(dir)) {
dir.split(path.sep).reduce(function (currentPath, folder) {
currentPath += folder + path.sep;
if (!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
return currentPath;
}, '');
}
};
var config = fs.readFileSync('config.xml').toString();
var name = getValue(config, 'name');
var IOS_DIR = 'platforms/ios';
var ANDROID_DIR = 'platforms/android';
var PLATFORM = {
IOS: {
dest: [
IOS_DIR + '/' + name + '/Resources/GoogleService-Info.plist',
IOS_DIR + '/' + name + '/Resources/Resources/GoogleService-Info.plist'
],
src: [
'GoogleService-Info.plist',
IOS_DIR + '/www/GoogleService-Info.plist',
'www/GoogleService-Info.plist'
]
},
ANDROID: {
dest: [
ANDROID_DIR + '/google-services.json',
ANDROID_DIR + '/app/google-services.json',
],
src: [
'google-services.json',
ANDROID_DIR + '/assets/www/google-services.json',
'www/google-services.json'
],
stringsXml: ANDROID_DIR + '/app/src/main/res/values/strings.xml'
}
};
// Copy key files to their platform specific folders
if (directoryExists(IOS_DIR)) {
copyKey(PLATFORM.IOS);
}
if (directoryExists(ANDROID_DIR)) {
copyKey(PLATFORM.ANDROID, updateStringsXml)
}
function updateStringsXml(contents) {
var json = JSON.parse(contents);
var strings = fs.readFileSync(PLATFORM.ANDROID.stringsXml).toString();
// strip non-default value
strings = strings.replace(new RegExp('<string name="google_app_id">([^\#<]+?)</string>', 'i'), '');
// strip non-default value
strings = strings.replace(new RegExp('<string name="google_api_key">([^\#<]+?)</string>', 'i'), '');
// strip empty lines
strings = strings.replace(new RegExp('(\r\n|\n|\r)[ \t]*(\r\n|\n|\r)', 'gm'), '$1');
// replace the default value
strings = strings.replace(new RegExp('<string name="google_app_id">([^<]+?)</string>', 'i'), '<string name="google_app_id">' + json.client[0].client_info.mobilesdk_app_id + '</string>');
// replace the default value
strings = strings.replace(new RegExp('<string name="google_api_key">([^<]+?)</string>', 'i'), '<string name="google_api_key">' + json.client[0].api_key[0].current_key + '</string>');
fs.writeFileSync(PLATFORM.ANDROID.stringsXml, strings);
}
function copyKey(platform, callback) {
for (var i = 0; i < platform.src.length; i++) {
var file = platform.src[i];
if (fileExists(file)) {
try {
var contents = fs.readFileSync(file).toString();
try {
platform.dest.forEach(function (destinationPath) {
var folder = destinationPath.substring(0, destinationPath.lastIndexOf('/'));
fs.ensureDirSync(folder);
fs.writeFileSync(destinationPath, contents);
});
} catch (e) {
// skip
}
callback && callback(contents);
} catch (err) {
console.log(err)
}
break;
}
}
}
function getValue(config, name) {
var value = config.match(new RegExp('<' + name + '>(.*?)</' + name + '>', 'i'));
if (value && value[1]) {
return value[1]
} else {
return null
}
}
function fileExists(path) {
try {
return fs.statSync(path).isFile();
} catch (e) {
return false;
}
}
function directoryExists(path) {
try {
return fs.statSync(path).isDirectory();
} catch (e) {
return false;
}
}
For fixing the issue:
Make sure you have copied the above file in "plugins" folder as cordova copies all the cordova-plugins from node_modules directory to plugins directory,
if you have already added the platforms before modifying the file
plugins/cordova-plugin-fcm/scripts/fcm_config_files_process.js, you need to remove the platforms and add again.
#Ari In case you are still having this issue, this is what I did to solve this issue.
I had to edit file "fcm_config_files_process.js" located in folder "plugins/cordova-plugin-fcm/scripts/":
// fs.writeFileSync("platforms/ios/" + name + "/Resources/GoogleService-Info.plist", contents)
For some unknown reason while building the project this line (42) was throwing the error "Invalid data, chunk must be a string or buffer, not object" so what I did was to comment that line and then manually copy the file "GoogleService-Info.plist" to "platforms/ios/" + name + "/Resources/"
Hope this help.
We had this error because our Development Push Certificate from apple was outdated. We have renewed it – and it worked.
Remove default added ios platform when creating Ionic 2 app then add again.
And also remove and add "cordova-fcm-plugin".
ionic platform rm ios
ionic platform add ios

How to add Content Security Policy to Firefox extension

I have a plugin which I have to support both on Chrome and Firefox browsers. The plugin does cross script loading.
In Chrome, by adding the content security policy in my manifest.json file, I could get away with it. How can I do it Firefox extension?
I couldn't find a simple solution for my problem and upon looking up some firefox plugin extensions i had to come up with my own solution as below. The below solution was tested on FF 24.0 but should work on other versions as well.
Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService)
.addObserver(_httpExamineCallback, "http-on-examine-response", false);
function _httpExamineCallback(aSubject, aTopic, aData) {
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
if (httpChannel.responseStatus !== 200) {
return;
}
var cspRules;
var mycsp;
// thre is no clean way to check the presence of csp header. an exception
// will be thrown if it is not there.
// https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIHttpChannel
try {
cspRules = httpChannel.getResponseHeader("Content-Security-Policy");
mycsp = _getCspAppendingMyHostDirective(cspRules);
httpChannel.setResponseHeader('Content-Security-Policy', mycsp, false);
} catch (e) {
try {
// Fallback mechanism support
cspRules = httpChannel.getResponseHeader("X-Content-Security-Policy");
mycsp = _getCspAppendingMyHostDirective(cspRules);
httpChannel.setResponseHeader('X-Content-Security-Policy', mycsp, false);
} catch (e) {
// no csp headers defined
return;
}
}
};
/**
* #var cspRules : content security policy
* For my requirement i have to append rule just to 'script-src' directive. But you can
* modify this function to your need.
*
*/
function _getCspAppendingMyHostDirective(cspRules) {
var rules = cspRules.split(';'),
scriptSrcDefined = false,
defaultSrcIndex = -1;
for (var ii = 0; ii < rules.length; ii++) {
if ( rules[ii].toLowerCase().indexOf('script-src') != -1 ) {
rules[ii] = rules[ii] + ' <My CSP Rule gets appended here>';
scriptSrcDefined = true;
}
if (rules[ii].toLowerCase().indexOf('default-src') != -1) {
defaultSrcIndex = ii;
}
}
// few publishers will put every thing in the default (default-src) directive,
// without defining script-src. We need to modify those as well.
if ((!scriptSrcDefined) && (defaultSrcIndex != -1)) {
rules[defaultSrcIndex] = rules[defaultSrcIndex] + ' <My CSP rule gets appended here>';
}
return rules.join(';');
};
There are plans in the future to add content policy natively in the SDK (bug 852297), but there is a 3rd party module that should get you close to where you want to be: policy.js

dart2js compiled code running in an unsupported browser

What happens if I try to run my generated javascript code in an unsupported browser? Like IE6?
I don't want to end up in a situation that my users will see a partly working broken app. Is there a way how to ensure that the dart/javascript will run only if the browser is supported and have my app degrade gracefully to some html banner "use a newer browser please" if it is not?
You could use the browser detector script here: http://www.quirksmode.org/js/detect.html
I wrote this code from the top of my head, I don't have a testing machine at my disposal right now:
var isNewFirefox = BrowserDetect.browser === 'Firefox' && BrowserDetect.version >= 7;
var isNewChrome = BrowserDetect.browser === 'Chrome';
var isNewIE = BrowserDetect.browser === 'Explorer' && BrowserDetect.version >= 9;
var isNewSafari = BrowserDetect.browser === 'Safari' && BrowserDetect.version >= 5.1;
var isNewOpera = BrowserDetect.browser === 'Opera' && BrowserDetect.version >= 12;
if (isNewFirefox || isNewChrome || isNewIE || isNewSafari || isNewOpera) {
var script = document.createElement('script');
if (navigator.webkitStartDart || navigator.startDart || navigator.mozStartDart || navigator.oStartDart || navigator.msStartDart) {
// Load Dart code!
script.setAttribute('type', 'application/dart');
script.setAttribute('src', 'http://.../foo.dart');
} else {
// Load dart2js code!
script.setAttribute('src', 'http://.../foo.js');
}
document.body.appendChild(script);
} else {
alert('Application wont work');
}
The version information can be found on: http://www.dartlang.org/support/faq.html#what-browsers-supported
Dart VM detection: http://www.dartlang.org/dartium/#detect
You can always detect browser in pure javascript and do not run dart program till you make sure browser is valid.

jquery mobile plugin creation

I am trying to create a plugin for JQuery Mobile. Does anyone have a template or examples to help? Currently, I have the following defined in myplugin.js
(function ($) {
$.fn.myPlugin = function (options) {
var defaults = { e: 0 },
settings = $.extend({}, defaults, options);
var h= $.myPlugin.getHtml(options.e);
alert("here 1");
if ((h != null) && (h != undefined) && (h.length > 0)) {
alert("here 2");
this.html(h);
}
};
$.myPlugin = {
getHtml: function (e) {
var s = "";
return s;
}
};
})(jQuery);
I am trying to initialize an instance of this plugin like such:
$("#pluginInstance", "#myPage").myPlugin({ e: 0 });
Oddly, neither alert dialog appears. There aren't any errors in the console either. What am I doing wrong?
How about this or this?
If you look how JQM is designed, the syntax is pretty similar. I'm also sticking with it, when working on plugins I'm doing.

Resources