Using SparkJS in browser

Hi Guys,

Does anyone have an example on how to use SparkJS in a web browser? I have tried to follow the documentation but it seems to be more relevant to NodeJS than a browser…

Basically I want to build an HTML5 app that connects to my core using a token and then runs a function and also retrieves various variables.

When I tried to follow the documentation I quickly ran into an issue as you cannot use require() in a web browser? without the spark variable declared I couldn’t use spark.login()

Thanks :slight_smile:

1 Like

This is some working code for the login. Perhaps this can help you further(?)

<html>
  <head>
    <title>Spark Login Example</title>    
  </head>

  <body>
    <div id="spark-login"></div>
  </body>	
  
  <script src="http://cdn.jsdelivr.net/sparkjs/0.2.0/spark.min.js"></script>
    <script>
      sparkLogin(function(data) {
        console.log(data);
      });
    </script>
</html>

[edit: use this URL for the source: http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js Notice the different version number.]

Unfortunately that just seems to simply present a login screen, where as I want to use tokens and the functions directly…

I assume the above example the JS dynamically picks up the div tag and then adds extra components

It was meant to be more of a proof of concept to show that it was actually working. If you check the console, you’ll see that it returns your accesstoken, which you can then use to get your functions/variables and fire them.

Once you’ve loaded the script, you should be able to use the functions mentioned in the docs. The following things work for me, which lead me to believe the rest should work as well.

<html>
  <head>
    <title>Spark Login Example</title>    
  </head>

  <body>
<!--    <div id="spark-login"></div>   -->
  </body>	
  
  <script src="http://cdn.jsdelivr.net/sparkjs/0.2.0/spark.min.js"></script>
    <script>
	/* ===========================================================
	var callback = function(err, body) {
	  console.log('API call login completed on callback:', body);
	};

	spark.login({username: 'name@provider.com', password: 'YourPassword'}, callback);
	*/// =========================================================
	
	
	/*
	spark.login({username: 'name@provider.com', password: 'YourPassword'}).then(
	  function(token){
		console.log('API call completed on promise resolve: ', token);
	  },
	  function(err) {
		console.log('API call completed on promise fail: ', err);
	  }
	);
	*///==========================================================
	
	spark.on('login', function(err, body) {
		console.log('API call completed on Login event:', body);
	  
		var devicesPr = spark.listDevices();

		devicesPr.then(
		  function(devices){
			console.log('Devices: ', devices);
		  },
		  function(err) {
			console.log('List devices call failed: ', err);
		  }
		);
		
		var devicesAt = spark.getAttributesForAll();

		devicesAt.then(
		  function(data){
			console.log('Core attrs retrieved successfully:', data);
		  },
		  function(err) {
			console.log('API call failed: ', err);
		  }
		);
		
		
	});

	spark.login({username: 'name@provider.com', password: 'YourPassword'});
		
	/*
      sparkLogin(function(data) {
        console.log(data);
      });
	  
	*/
    </script>
</html>

That produces the following:

Using that, you should be able to call the functions of your liking.

1 Like

Thanks for that, I was able to get that working fine, however spark.getDevice doesn’t appear to be working? I had a look in the spark.js file and couldn’t find any reference of that function?

  <html>
  <head>
    <title>Spark Login Example</title>    
  </head>

  <body>
  </body>	
  
  <script src="http://cdn.jsdelivr.net/sparkjs/0.2.0/spark.min.js"></script>
    <script>

	
	spark.on('login', function(err, body) {
		console.log('API call completed on Login event:', body);
	  
		spark.listDevices(function(err, devices) {
			  var device = devices[0];
			
			  console.log('Device name: ' + device.name);
			  console.log('- connected?: ' + device.connected);
			  console.log('- variables: ' + device.variables);
			  console.log('- functions: ' + device.functions);
			  console.log('- version: ' + device.version);
			  console.log('- requires upgrade?: ' + device.requiresUpgrade);
			});

		spark.getDevice('54ff6e066678574918123456', function(err, device) {
			  console.log('Device name: ' + device.name);
			});	
		
	});

	//spark.login({username: 'xxx@xxx.net', password: 'xxx'});
	spark.login({accessToken: '57a8aed6971a0e997a659f467fc5cbb4ea123456'});
	
	/*
      sparkLogin(function(data) {
        console.log(data);
      });
	  
	*/
    </script>
</html>

This is the console log

[Log] API call completed on Login event:  (test.html, line 14)
Object

[Error] TypeError: undefined is not a function (evaluating 'spark.getDevice('54ff6e066678574918123456', function(err, device) {
			  console.log('Device name: ' + device.name);
			})')
	(anonymous function) (test.html, line 27)
	emit (spark.min.js, line 2)
	emitAndCallback (spark.min.js, line 1)
	(anonymous function) (spark.min.js, line 1)
	(anonymous function) ([native code], line 0)
	login (spark.min.js, line 1)
	global code (test.html, line 34)
[Log] Device name: tasty_station (test.html, line 19)
[Log] - connected?: false (test.html, line 20)
[Log] - variables: undefined (test.html, line 21)
[Log] - functions: undefined (test.html, line 22)
[Log] - version: undefined (test.html, line 23)
[Log] - requires upgrade?: undefined (test.html, line 24)

Ok so I worked it out, appears the documentation is incomplete and still references the older 0.2.0 release rather than the 0.2.4 release which is when the getDevice function was added

<script type="text/javascript" src="//cdn.jsdelivr.net/sparkjs/0.2.0/spark.min.js">

Release History

Version 0.1.0 Initial release Version 0.2.1 Publishing, test release Version 0.2.2 Pulling in getDevice Version 0.2.4 adding some basic parsing to the getEventStream function, now returns an object

How do we go about submitting a bug report on the documentation?

You’re absolutely correct! I hadn’t noticed that myself since I have the library locally. You can make Pull Request by clicking the “edit this page” button at the top right of the docs page.
Seeing as I apparently have editorial rights on the docs, I went ahead and changed it. I guess the docs get updated every X time, so it should probably show up in a while. (Could you verify/check this @kennethlimcp?)

Thanks that looks much better now :slight_smile:

Is it possible to also get your second example included in the documentation as that example instantly provided all the components I needed to get my code working

<html>
  <head>
    <title>Spark Login Example</title>    
  </head>

  <body>
<!--    <div id="spark-login"></div>   -->
  </body>	
  
  <script src="http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js"></script>
    <script>
	/* ===========================================================
	var callback = function(err, body) {
	  console.log('API call login completed on callback:', body);
	};

	spark.login({username: 'name@provider.com', password: 'YourPassword'}, callback);
	*/// =========================================================
	
	
	/*
	spark.login({username: 'name@provider.com', password: 'YourPassword'}).then(
	  function(token){
		console.log('API call completed on promise resolve: ', token);
	  },
	  function(err) {
		console.log('API call completed on promise fail: ', err);
	  }
	);
	*///==========================================================
	
	spark.on('login', function(err, body) {
		console.log('API call completed on Login event:', body);
	  
		var devicesPr = spark.listDevices();

		devicesPr.then(
		  function(devices){
			console.log('Devices: ', devices);
		  },
		  function(err) {
			console.log('List devices call failed: ', err);
		  }
		);
		
		var devicesAt = spark.getAttributesForAll();

		devicesAt.then(
		  function(data){
			console.log('Core attrs retrieved successfully:', data);
		  },
		  function(err) {
			console.log('API call failed: ', err);
		  }
		);
		
		
	});

	spark.login({username: 'name@provider.com', password: 'YourPassword'});
		
	/*
      sparkLogin(function(data) {
        console.log(data);
      });
	  
	*/
    </script>
</html>

Glad I could be of assistance :smiley:!
Technically I could paste it in there, but I guess it’ll have to be cleaned up a fair bit, and have some peer review with the other Elites before I try that. Don’t want to mess up the docs, but I agree that some more examples might not be out of place. My example would’ve also helped me when I just started out (which is not too long ago ;P).
You can of course always make Pull Requests if you feel you’ve got something meaningful to add. I’ll take a look at this as well :blush:

1 Like

Ok so I am back... appears none of my call back functions will be accepted by the spark.js :frowning:

spark.on('login', function(err, body) {
  console.log('API call completed on Login event:', body);
  spark.getEventStream(false, false, function(data) {
	  console.log("Event: " + data);
	});
});

spark.login({accessToken: '57a8aed6971a0e997a659f467fc5cbb41234567});

[Log] API call completed on Login event: (test.html, line 9)
Object

[Error] Error: Bad callback given: undefined
request (spark.min.js, line 1)
getEventStream (spark.min.js, line 1)
getEventStream (spark.min.js, line 1)
(anonymous function) (test.html, line 10)
emit (spark.min.js, line 2)
emitAndCallback (spark.min.js, line 1)
(anonymous function) (spark.min.js, line 1)
(anonymous function) ([native code], line 0)
login (spark.min.js, line 1)
global code (test.html, line 15)

That indeed is strange. That I’ve looked at the library but can’t figure out why it’s giving the error. I guess it’s time to call in the reinforcements: @kennethlimcp @peekay123 @Dave @ScruffR @bko Could one of you perhaps take a look at it? The code above is basically the same as in the examples provided.

2 Likes

@solojavier might be able to quickly look at this but I’ll test it as well

Nothing really jumped out at me. Where you have

<script scr="...path to .js..."></script>

I always try to help out with more hints just in case:

<script scr="...path to .js..." type="text/javascript" charset="utf-8"></script>

If I were debugging this, I would do it using the Chrome Javascript debug console which is quite nice.

I did troubleshoot before I posted but forgot to include the details, it seems all the Spark event functions have the same issue as they all link to a common function that seems to be failing?

Can anyone confirm they are having the same issues when they put the code into a HTML page? I tried to keep the snippet as simple as possible to allow it to be easily debugged

@semaja2,

This is kind of messy looking at only snippets of your code. Can you have a full sample of the non-working code?

My test on nodejs worked fine so far

This should be a ‘complete’ example, which doesn’t work:

<html>
  <head>
    <title>Spark Login Example</title>    
  </head>

  <body>
	Open the console to see output.
  </body>	
  
  <script src="http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js" type="text/javascript" charset="utf-8"></script>
    <script>
	spark.on('login', function() {
	    console.log("I've just logged in. Now I'll try to subscribe to all events.");
		
	    //Get all events
	    spark.getEventStream(false, false, function(data) {
		console.log("Event: " + JSON.stringify(data));
	    });
/*
	    //Get your devices events
	    spark.getEventStream(false, 'mine', function(data) {
	        console.log("Event: " + JSON.stringify(data));
	    });
	   
            //Get test event for specific core
	    spark.getEventStream('test', 'CORE_ID', function(data) {
		console.log("Event: " + JSON.stringify(data));
	    });
*/
	});

        // Login as usual
        spark.login({ username: 'mail@provider.com', password: 'pass'});
        //spark.login({ accessToken: '012345' });
		
    </script>
</html>

Several other functions work fine, although the listDevices gave some problems since it doesn’t return the functions/variables like it’s supposed to. getDevice on the other hand does work.

1 Like

@Moors7 and @semaja2,

I’m really just guessing that the way spark.min.js V0.2.4 was bumped did not end up in cdn…

@Dave updated the file AFTER bumping the version to V0.2.4 so i’m guessing the change would not have been picked up: https://github.com/spark/sparkjs/commit/20c89ad985e3a388c77ca1dd12c04f7cad33d164

Using NodeJS works since the library is pulled from the github repo directly during install so we are safe to conclude that the functions works ok…

Let’s wait for an official Spark reply for now.

1 Like

I actually tried the latest spark.min.js from the git and it still has the same issue, I wonder if there is a bug that only shows up when using it outside of NodeJS?

Hmm, strange! I’ll dive into it as soon as I get a chance tomorrow, I added an issue for this here:

Thanks,
David

3 Likes

Hey @dave, did you have a chance to look at this already? The eventStream is still acting weird. I tried to use the code you supplied yesterday in the browser, but I keep getting errors about the callback functions.
Using this (from the docs):

spark.getEventStream(false, false, function(data) {
    console.log("Event: " + data);
});

gives me this error in the console:

Potentially unhandled rejection [1] Error: Bad callback given: undefined
    at request (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:1:23577)
    at SparkApi.getEventStream (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:1:7112)
    at Spark.getEventStream (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:1:21683)
    at file:///C:/Users/jordy/Documents/sparkjs/events.html:17:10
    at http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:1:12041
    at tryCatchReject (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:7:13954)
    at runContinuation1 (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:7:13469)
    at Fulfilled.when (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:7:10707)
    at Pending.run (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:7:9155)
    at runQueue (http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js:6:24063)