# Using SparkJS in browser

**URL:** <https://community.particle.io/t/using-sparkjs-in-browser/9004>\
**Category:** Getting Started\
**Created:** [December 28, 2014, 4:07am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004 "2014-12-28T04:07:13Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 28, 2014, 4:07am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/1 "2014-12-28T04:07:13Z")

</div>

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 🙂

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [December 28, 2014, 10:33pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/2 "2014-12-28T22:33:44Z")

</div>

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

```auto
<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](http://cdn.jsdelivr.net/sparkjs/0.2.4/spark.min.js) Notice the different version number.]_

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 28, 2014, 10:50pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/3 "2014-12-28T22:50:00Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [December 29, 2014, 12:10am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/4 "2014-12-29T00:10:34Z")

</div>

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.

```auto
<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:

![](https://sea2.discourse-cdn.com/flex026/uploads/particle/3982/663d2c20a4cb5f73.png)

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

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 29, 2014, 3:32am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/5 "2014-12-29T03:32:40Z")

</div>

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?

```auto
  <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

```auto
[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)

```

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 29, 2014, 9:02pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/6 "2014-12-29T21:02:50Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [December 29, 2014, 9:33pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/7 "2014-12-29T21:33:59Z")

</div>

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](https://github.com/spark/docs/blob/master/src/content/javascript.md) @kennethlimcp?)

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 29, 2014, 9:41pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/8 "2014-12-29T21:41:22Z")

</div>

Thanks that looks much better now 🙂

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

```auto
<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>

```

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [December 29, 2014, 9:49pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/9 "2014-12-29T21:49:34Z")

</div>

Glad I could be of assistance 😃!  
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 😊

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 30, 2014, 8:32am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/10 "2014-12-30T08:32:42Z")

</div>

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

```ccp
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)

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [December 30, 2014, 10:00pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/11 "2014-12-30T22:00:12Z")

</div>

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](https://github.com/spark/sparkjs/blob/master/examples/node/get-event-stream.js) provided.

---

<div class="post-metadata">

**Author:** ![kennethlimcp](https://avatars.discourse-cdn.com/v4/letter/k/c0e974/32.png) [@kennethlimcp](https://community.particle.io/u/kennethlimcp)\
**Post date:** [December 30, 2014, 10:57pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/12 "2014-12-30T22:57:00Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![bko](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/bko/32/20704_2.png) [@bko](https://community.particle.io/u/bko)\
**Post date:** [December 30, 2014, 11:00pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/13 "2014-12-30T23:00:08Z")

</div>

Nothing really jumped out at me. Where you have

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

```

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

```auto
<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.

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 30, 2014, 11:23pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/14 "2014-12-30T23:23:04Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kennethlimcp](https://avatars.discourse-cdn.com/v4/letter/k/c0e974/32.png) [@kennethlimcp](https://community.particle.io/u/kennethlimcp)\
**Post date:** [December 30, 2014, 11:41pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/15 "2014-12-30T23:41:08Z")

</div>

@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

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [December 31, 2014, 12:10am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/16 "2014-12-31T00:10:36Z")

</div>

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

```auto
<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](http://docs.spark.io/javascript/#supported-commands-device-object) gave some problems since it doesn’t return the functions/variables like it’s supposed to. `getDevice` on the other hand does work.

---

<div class="post-metadata">

**Author:** ![kennethlimcp](https://avatars.discourse-cdn.com/v4/letter/k/c0e974/32.png) [@kennethlimcp](https://community.particle.io/u/kennethlimcp)\
**Post date:** [December 31, 2014, 12:52am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/17 "2014-12-31T00:52:45Z")

</div>

@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](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.

---

<div class="post-metadata">

**Author:** ![semaja2](https://avatars.discourse-cdn.com/v4/letter/s/b4bc9f/32.png) [@semaja2](https://community.particle.io/u/semaja2)\
**Post date:** [December 31, 2014, 2:05am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/18 "2014-12-31T02:05:08Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Dave](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/dave/32/181_2.png) [@Dave](https://community.particle.io/u/Dave)\
**Post date:** [December 31, 2014, 6:09am UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/19 "2014-12-31T06:09:06Z")

</div>

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

> <https://github.com/particle-iot/sparkjs/issues/40>

Thanks,  
David

---

<div class="post-metadata">

**Author:** ![Moors7](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/moors7/32/588_2.png) [@Moors7](https://community.particle.io/u/Moors7)\
**Post date:** [January 15, 2015, 3:25pm UTC](https://community.particle.io/t/using-sparkjs-in-browser/9004/20 "2015-01-15T15:25:27Z")

</div>

Hey @dave, did you have a chance to look at this already? The eventStream is still acting weird. I tried to use [the code](http://community.spark.io/t/lost-event-stream-solved/9304/4) you supplied yesterday in the browser, but I keep getting errors about the callback functions.  
Using this (from the docs):

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

```

gives me this error in the console:

```auto
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)

```

[Next page](https://community.particle.io/t/using-sparkjs-in-browser/9004.md?page=2)
