Plugin not working - javascript

I have installed Rand Dusing's BLE Cordova Plugin and following his example to initialize bluetooth but I cannot get past that. Here is my index.js
var blePlugin = window.bluetoothle;
function bleInitialize() {
var paramsObj = {
request: true,
statusReceiver: true
};
document.getElementById("BTHWStatus").innerHTML = 'Initialze BLE: Checking BT status...';
blePlugin.initialize(bleInitializeSuccess, bleInitializeError, paramsObj);
document.getElementById("BTHWStatus").innerHTML = 'Initialze BLE: Complete';
return false;
}
function bleInitializeSuccess(obj) {
if (obj.status == "enabled")
document.getElementById("BTHWStatus").innerHTML = 'BT is turned ON';
else
document.getElementById("BTHWStatus").innerHTML = 'BLE:Initialize: Unexpected error';
}
function bleInitializeError(obj) {
document.getElementById("BTHWStatus").innerHTML = "Initialize Error : " + JSON.stringify(obj);
}
This is index.html
<h3>Bluetooth Test App</h3>
<br>
<div>
<a id="BTHWStatus">BT is turned OFF</a>
<br/>
<br/>
<span>Enable/Disable Bluetooth :</span>
<input type="checkbox" id="BTSelect">
<button id="BTApply">Apply</button>
<br/>
</div>
Can anyone tell me if I have anything incorrect in theindex.js file that may prevent the plugin to not work? I have verified that the plugin is installed correctly in the command prompt using command cordova plugin.
Are the callback functions coded correctly or did I miss something? I can get the blePlugin.initialize function to print Initialze BLE: Checking BT status... on the app page but nothing after that.
Thanks and appreciate your help.

Is your application code executed after the deviceready event? From your code I can't see it so the problem could be this.
If you don't wait for the deviceready event, the js code will work but the Cordova related functions will be not available.

Related

Javascript type error - The "listener" argument must be of type Function. Received type object

I am trying to create a URL shortener using jsonbase.com and vanilla javascript.
button tag in HTML was not able to recognize the method "shortUrl" from my js file. So, I directly added the code of add event listener in the js file.
index.html
<body>
<div id="app">
<input type="url" id="urlinput">
<input id="mybutton" type="button" value="Short the URL"/>
</input>
</div>
<script src="src/index.js"></script>
</body>
Now, I am getting an error - Javascript type error - The "listener" argument must be of type Function. Received type object - when I am trying to use jsonbase.com for storing the data.
script.js
function shortUrl() {
var longurl = getURL();
genHash();
var uniqueHash = window.location.hash.substr(1);
sendRequest(longurl, uniqueHash);
if (window.location.hash !== "") {
var short = getRequest(uniqueHash);
if (short !== "") {
window.location.herf = "short";
}
}
}
use of jsonbase.com
var jsonbase = require("jsonbase.com");
var token = "mytoken";
var store = jsonbase(token);
var endpoint = `jsonbase.com/${token}`;
//sending request
function sendRequest(longURL, uniqueHash) {
store.write(`${endpoint}/${uniqueHash}`, longURL);
}
//getting request
function getRequest(uniqueHash) {
return store.read(`${endpoint}/${uniqueHash}`).then((response) => {
return response.data;
});
}
generating hash for shorter
function genHash() {
if (window.location.hash === "") {
window.location.hash = getRandomStr();
}
}
Error screenshot -
I have created a reproducible sample code sandbox for my private application - https://codesandbox.io/s/url-shortner-t3ov2
Please let me know if any more info is required.
The issue is not your code, the issue is the package not parsing the JSON correctly, try using a different package
I know this does not answer your question, but it should solve it

angucomplete undesirable click event fires

Recently, I am implementing autocomplete on my search using angucomplete, now the desired output that I wish to achieve is that whenever I select one of the autocomplete suggestions by clicking the mouse, it would navigate to the desire url or let's say google.com for test purposes. The problem with code below is that when I click the textbox without selecting any suggestions, navToUrlByClick function will fire. Any suggestions and sorry for this kind of question since the writer just started to explore javascript. Thanks in advance!
This is my test.html code:
<div class="padded-row" ng-click="navToUrlByClick('http://www.google.com')">
<div angucomplete-alt id="ex5"
placeholder="Search projects"
pause="50"
selected-object="selectedProject"
remote-url="http://localhost:5000/"
remote-url-request-formatter="remoteUrlRequestFn"
remote-url-data-field="items"
title-field="subs_name"
minlength="1"
input-class="form-control form-control-small"
match-class="highlight">
</div>
</div>
And this is my app.js code:
$scope.navToUrlByClick = function(str){
if ((str != "") || (str != null))
{
console.log(str)
//$window.location.href = str;
}
}
I figure it out by using callback with the few lines of code below and added to my app.js
$scope.selectedProject = function(selected) {
if (selected) {
// window.alert('You have selected ' + selected.title);
$window.location.href = "http://www.google.com";
} else {
console.log('cleared');
}
};
Case closed!

how to automatically record a video response after the video stops playing using flash

Using Mediaelementjs, i have successfully implemented a videoplayer, and triggered an end event which immediately pops up a flash recorder of adobe. Listing the website in Website Privacy Settings panel gives the direct access to microphone and camera via browser.
Question:
Is there a way to trigger certain function after the access to microphone and camera is allowed by the user, like start recording the video?
Can we somehow get to record the video immediately after user allows access to microphone and camera using flash.
My answer would be of low quality, because I lost interest for Flash many years ago. The most polite way to put it: my skills of Flash are rusty. (by rusty, I mean Flash-8 ActionScript 2.0 / Flash CS4 ActionScript 2.0 level of rusty). What poses a real problem - I have no testing environment for Flash on my current computer. Thus, this would be a blind advice. Beware of bugs.
But, on the bright side, I did have experience of integrating Flash and Javascript. From what I see some of that is still relevant.
Short list of techniques that I know:
Javascript to Flash:
ExternalInterface object provided by Flash allows Javascript execute methods inside of Flash
- this could start animation or return data.
Drawback: ExternalInterface could be prohibited by security settings or buggy implementation of plugin.
document.getElementById('exampleMovie').SetVariable("someVariableName", "some text");
- to use this as message system - add Flash timer which would be listening -
did a varialbe change
Flash to Javascript:
ExternalInterface object provided by Flash allows Flash execute functions from Javascript.
Drawback: ExternalInterface could be prohibited by security settings or buggy implementation of plugin.
getUrl( 'javascript:someJavascriptFunction( "a", "b", true );' );
I am not sure if it was banned for security reasons but
it could work. main drawback is that it's a one-way interaction.
I think that using External Interface is most logical way of implementing interaction.
Yes, you could use one-way interactions 2. and 2. to build communication protocol - I can even imagine that system... but that would be a bit too perverse ^ ^. + I can't find any data about browser support for 'SetVariable'. + Stackoverflow has a report of weird behavior of SetVariable in firefox SetVariable is not working in Firefox
Here is oficial documentation for External Interface:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html
That page has a browser compatibility table. Perhaps documentation needs update - no traces of Google Chrome which feels weird in my opinion...
Conceptually, you use External Interface like that:
// HTML
// id must be equal to name here
// and shouldn't contain symbols . - + * / \
<object id="exampleFlash" name="exampleFlash" ... >
...
</object>
// Javascript:
document.getElementById('exampleFlash').methodExposedForJavascript('value')
// ActionScript in Flash:
import flash.external.ExternalInterface;
ExternalInterface.addCallback( "methodExposedForJavascript", someInternalFunction );
function someInternalFunction( msg ) {
// do something with msg - for example output it to existing txt field:
_root.txtExampleTxt.text = msg;
}
The most relevant example is the last on that manual page http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html
Short instruction how to compile complex examples like that: http://help.adobe.com/en_US/as3/dev/WS9b644acd4ebe5999-2734bf3c124372a52ff-8000.html
They actually quite simple. Most percieved complexity comes from the fact that they generate elements of Flash programmatically - like
// all that this code does - is creating simple TextField in your movie
import flash.text.TextField;
package {
public class ABC extends Sprite
{
private var output:TextField;
public function ABC()
{
output = new TextField();
output.y = 25;
output.width = 450;
addChild(output);
}
}
}
This is done to make examples easier to express - but this is basically the same as 'use your GUI to create text field named output in your first frame'.
I'll try to cut away anything unrequired from that example.
Pay attention to "receivedFromJavaScript" - this is a function that will be triggered by Javascript - you can add reaction inside.
Flash part:
package {
import flash.display.Sprite;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.text.TextField;
import flash.utils.Timer;
import flash.text.TextFieldType;
import flash.text.TextFieldAutoSize;
import flash.system.Security;
public class ExternalInterfaceExample extends Sprite
{
private var output:TextField;
public function ExternalInterfaceExample()
{
// constructor code
Security.allowDomain("*");
output = new TextField();
output.y = 25;
output.width = 450;
output.height = 325;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.text = "Initializing...\n";
addChild(output);
if (ExternalInterface.available) {
try {
output.appendText("Adding callback...\n");
ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);
if (checkJavaScriptReady()) {
output.appendText("JavaScript is ready.\n");
} else {
output.appendText("JavaScript is not ready, creating timer.\n");
var readyTimer:Timer = new Timer(100, 0);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
} catch (error:SecurityError) {
output.appendText("A SecurityError occurred: " + error.message + "\n");
} catch (error:Error) {
output.appendText("An Error occurred: " + error.message + "\n");
}
} else {
output.appendText("External interface is not available for this container.");
}
}
private function receivedFromJavaScript(value:String):void {
output.appendText("JavaScript says: " + value + "\n");
}
private function checkJavaScriptReady():Boolean {
var isReady:Boolean = ExternalInterface.call("isReady");
return isReady;
}
private function timerHandler(event:TimerEvent):void {
output.appendText("Checking JavaScript status...\n");
var isReady:Boolean = checkJavaScriptReady();
if (isReady) {
output.appendText("JavaScript is ready.\n");
output.appendText("ExternalInterface.objectID = " + ExternalInterface.objectID + "\n");
Timer(event.target).stop();
}
}
}
}
HTML:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ExternalInterfaceExample</title>
<script>
var jsReady = false;
function isReady() {
return jsReady;
}
function pageInit() {
jsReady = true;
document.forms["form1"].output.value += "\n" + "JavaScript is ready.\n";
}
function sendToActionScript(value) {
document.getElementById("ExternalInterfaceExample").sendToActionScript(value);
}
</script>
</head>
<body onload="pageInit();">
<object id="ExternalInterfaceExample" name="ExternalInterfaceExample"
type="application/x-shockwave-flash" data="ExternalInterfaceExample.swf" width="550" height="400">
<param name="movie" value="ExternalInterfaceExample.swf"/>
<param name="quality" value="high"/>
<param name="allowscriptaccess" value="always"/>
<a href="http://www.adobe.com/go/getflash">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player"/>
</a>
</object>
<form name="form1" onsubmit="return false;">
<input type="text" name="input" value="" />
<input type="button" value="Send" onclick="sendToActionScript(this.form.input.value);" /><br />
<textarea cols="60" rows="20" name="output" readonly="true">Initializing...</textarea>
</form>
</body>
</html>

Uncaught twilio.exception wrong number of segments

I'm using Twilio to make a call from a browser to the phone. When I click call I get this error Uncaught twilio.exception wrong number of segments
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
Twilio.Device.setup('#token');
Twilio.Device.ready(function (device) {
$("#log").text("Client '#clientName' is ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended");
});
Twilio.Device.incoming(function (conn) {
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
function call() {
// get the phone number or client to connect the call to
params = { "PhoneNumber": $("#number").val() };
Twilio.Device.connect(params);
}
function hangup() {
Twilio.Device.disconnectAll();
}
</script>
<div class="hero-unit" style="background-color: white; margin-left: 650px;">
<div class="container">
<h3>Call us and watch us answer!</h3>
<p style="margin-left: -65px;">Use Twilio to call our office and watch us answer on camera!</p>
<button class="call" onclick="call();">
Call
</button>
<button class="hangup" onclick="hangup();">
Hangup
</button>
<input type="text" id="number" name="number"
placeholder="Enter a phone number or client to call" />
</div>
</div>
In the code behind I have:
public string TwilioToken
{
get
{
string accountSid = "*************";
string authToken = "*************";
string applicationSid = "************";
string clientName = "*****";
if (Request["client"] != null)
{
clientName = Request["client"];
}
var capability = new TwilioCapability(accountSid, authToken);
capability.AllowClientOutgoing(applicationSid);
capability.AllowClientIncoming(clientName);
return capability.GenerateToken();
}
}
Twilio evangelist here.
I can't quite tell how you are getting the value of the TwilioToken property to render in your HTML. In this line of the JavaScript:
Twilio.Device.setup('#token');
#token should be being replaced by the value being generated in your code-behind. Since you mention code-behind it sounds like you might be using WebForms. In order to render the value of the TwilioToken property in your HTML you'd need to use something like this syntax:
Twilio.Device.setup('<%= TwilioToken %>');
Once you do that when you load the page in a browser you should see that syntax replaced by a long encoded string of characters that Twilio uses to setup the JavaScript library.
Hope that helps.
The sample code shows lines like this:
$capability = new Services_Twilio_Capability($TWILIO_SID, $TWILIO_TOKEN);
$capability->allowClientOutgoing('APabe7650f654fc34655fc81ae71caa3ff');
$TOKEN = $capability->generateToken();
Followed by later on this:
Twilio.Device.setup("<?php echo $TOKEN; ?>");
I was getting this same error until I realized that I had misspelled $TOKEN and was passing a blank string to Twilio.Device.setup. After fixing it, the error went away.

JavaScript talking to Flash via ExternalInterface

I have been trying to put together a proof of concept of JavaScript talking to Flash. I am using JQuery and Flash CS5, ActionScript 3.
I am not a Flash developer so apologies for the code, if I can prove this works the Flash will be given to someone who knows what they are doing.
The Actionscript is on a layer in the timeline in the first frame, with a couple of elements in the root movie:
output = new TextField();
output.y = -200;
output.x = -200;
output.width = 450;
output.height = 325;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.text = "Initializing...\n";
root.bgClip.addChild(output);
try{
Security.allowDomain("*");
flash.external.ExternalInterface.marshallExceptions = true;
output.appendText("External Interface Available? " + ExternalInterface.available + "\n");
output.appendText("External Interface ObjectId: " + ExternalInterface.objectID + "\n");
flash.external.ExternalInterface.addCallback("getMenuItems", returnMenuItems);
flash.external.ExternalInterface.addCallback("changeText", changeText);
flash.external.ExternalInterface.addCallback("changeBgColour", changeBgColour);
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
} catch (error:SecurityError) {
output.appendText("Security Error: " + error.message + "\n");
} catch (error:Error) {
output.appendText("Error: " + error.message + "\n");
}
function returnMenuItems():String{
return "[{\"menu option\": \"javascript:callFlash('changeBgColour','4CB9E4')\"}]";
}
function changeText(t:String){
root.textClip.text = t;
}
function changeBgColour(colour:String) {
var c:ColorTransform = root.bgClip.transform.colorTransform;
c.color = uint(colour);
root.bgClip.transform.colorTransform = c;
}
The JavaScript and HTML are:
function populateMenu(message){
$("#options").changeType("Options", $.parseJSON(message));
$("#options").addMenuActions();
}
function callFlash(methodToCall, param){
alert("method: " + methodToCall + ", param: " + param);
if(param == undefined){
$("#AJC")[methodToCall]();
}else{
$("#AJC")[methodToCall](param);
}
}
var flashvars = {};
var params = {allowScriptAccess: "always"};
var attributes = {name: "AJC"};
swfobject.embedSWF("http://192.168.184.128/ActionscriptJavascriptCommunication.swf", "AJC", "600", "400", "9", "", flashvars, params, attributes);
and
<body>
<div id="wrapper">
<div id="topBar" class="top-bar"></div>
<div id="flashContainer">
<div id="AJC">Loading Flash...</div>
</div>
<ul class="dropdown" id="games"></ul>
<ul class="dropdown" id="options"></ul>
</div>
</body>
Now I know the ActionScript is awful, the reason it looks like it does is because I have read a lot of threads about possible issues to do with contacting Flash from JavaScript (hence the allow security domain * and adding a debug text box etc).
The JavaScript I am using is within a script tag in the head. The changeType and addMenuActions are just JQuery methods I have added. These are just JavaScript methods that have been tested independently but do work.
You'll notice that the last line of my try catch in the ActionScript is:
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
This does work, it populate my menu with the text sent from Flash. The only thing that doesn't work is trying to call the methods exposed using the addCallback function.
I get the alert which says:
method: changeBgColour, param: 4CB9E4
but an error saying:
Error: $("#AJC")[methodToCall] is not a function
Source File: http://192.168.184.128/test.html#
Line: 88
I set up a local VM to run Apache, which relates to the 192.168.184.128, I wondering if this was the issue, I have seen a couple of threads mention that trying to communicate with flash locally won't work, which is why I set up the VM with apache?
Any ideas? I know people have got this working, it is very frustrating.
Thanks.
Simple mistake: jQuery's factory method produces jQuery.init object, which acts very similar to an array. You need to call the method on the actual DOM element, which is the first member in the "array".
$('#AJC')[0][methodToCall]
If you had security issues, you wouldn't be able to communicate between Flash and JavaScript at all.
The problem is in the way you are accessing your flash object. SwfObject has a built-in function that take care of that, it works great across all browsers:
function callFlash(methodToCall, param)
{
var obj = swfobject.getObjectById("AJC");
if(param == undefined){
$(obj)[methodToCall]();
}else{
$(obj)[methodToCall](param);
}
}
I havent tested the code above, but I guess it should work!

Categories