Language - JavaScript Browser: Difference between revisions

From Phidgets Support
No edit summary
No edit summary
Line 1: Line 1:
[[Category:Language]]
{{NoTitle}}
{{NoTitle}}
{{Language_-_JavaScript_Dev_Environment_Table}}
{|
{|
|style="vertical-align:middle; width: 60%;"|
|style="vertical-align:middle; width: 60%;"|
<font size=6>'''Language - JavaScript'''
<font size=6>'''Language - JavaScript'''


'''In-Browser'''</font>
'''JavaScript with Browser'''</font>


Welcome to using Phidgets with Javascript! By using Javascript, you will have access to the complete Phidget22 API, including events.
Welcome to using Phidgets with JavaScript! By using JavaScript, you will have access to the complete Phidget22 API, including events.


Running your JavaScript program in a browser is accessible and can be done in Windows, macOS, or Linux.
Using JavaScript with a browser provides a good way to create a powerful web interface for your Phidgets programs.
|{{TOC limit|2}}
|{{TOC limit|2}}
|}
|}


==Install Phidget Drivers==
==Install Phidget Drivers for JavaScript in Browser==
Before getting started with the guides below, ensure you have the following components installed on your machine:
Before getting started with the guides below, ensure you have the following components installed on your machine:


* You will need the Phidgets drivers installed (choose your OS):
# You will need the [[Operating_System_Support|Phidgets Drivers]] installed on the server machine
** [[OS_-_Windows#Quick_Downloads|Windows Drivers]]
# You will need the [{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip Phidgets JavaScript Library for Browsers]
** [[OS_-_macOS#Quick_Downloads|macOS Drivers]]
** [[OS_-_Linux#Quick_Downloads|Linux Drivers]]


== Use Our Examples ==
One of the best ways to start programming with Phidgets is to use our example code as a guide:
* [{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser JavaScript Browser Examples]


== Editing the Examples ==
=== Version Change ===
'''Note:''' The Phidgets JavaScript library has been bumped to version 2.x.x following a rewrite. The version 2 API is mostly identical to version 1, but does have some breaking changes. It is highly recommended that any code written against version 1 be updated to version 2, as version 1 is considered unstable.


== Write Code ==  
== Phidget Network Server ==
The JavaScript library requires the [[Phidget Network Server]]. Start by configuring the server for your OS:


== Setting up a New Project ==
* [[OS - Windows#Phidget Network Server|Windows]]
* [[OS - OS X#Phidget Network Server|macOS]]
* [[OS - Linux#Phidget Network Server|Linux]]
* [[OS - Phidget SBC#Phidget Network Server|PhidgetSBC]]


== Further Reading ==
The Phidget Server includes a built-in Webserver. This must be enabled when using the JavaScript library in browser, but can be left disabled when using the library from Node.js.
[[Phidget Programming Basics]] - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.


[[Data Interval/Change Trigger]] - Learn about these two properties that control how much data comes in from your sensors.
The Phidget Server Webserver can be used to serve files - such as the Phidget JavaScript library, or your own projects. By default, it serves the JavaScript control panel files. The main purpose of the Webserver is to support a Websockets connection for the Browser library - because regular sockets cannot be used in Browser. The Node.js library uses raw sockets to connect to the Phidget Server, and so does not require the Webserver or Websockets.


[[Using Multiple Phidgets]] - It can be difficult to figure out how to use more than one Phidget in your program. This page will guide you through the steps.
== JavaScript Control Panel ==
The JavaScript control panel is a Browser version of our Phidget control panel. This can be used to view and control all Phidgets attached to a Phidget server. The JavaScript control panel is installed by default on Windows, macOS and PhidgetSBC. You can also download the source [{{SERVER}}/downloads/phidget22/tools/any/Phidget22JavaScriptControlPanel.zip here].


[[Polling vs. Events]] - Your program can gather data in either a polling-driven or event-driven manner. Learn the difference to determine which is best for your application.
Make sure the Phidget Server - Webserver is enabled, and running, then navigate to http://localhost:8989. You will now see a program written with JavaScript/HTML that mimics the Phidget Control Panel. It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch.


[[Logging, Exceptions, and Errors]] - Learn about all the tools you can use to debug your program.
[[File:Javascript_windows_controlpanel.png|link=|center]]


[[Phidget Network Server]] - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.
==Use Our Examples==
One of the best ways to start programming with Phidgets is to use our example code as a guide. Our browser examples are available [{{SERVER}}?view=code_samples&lang=JavaScript&os=Browser here].
 
== Write Your Own Code ==
Let's start by writing a simple HTML page that makes a dynamic list of attached Phidgets visible to the user.
We will be using the JavaScript library [https://jquery.com/download/ jQuery] in these examples. jQuery is not required in order to use Phidgets, however, it will make it easier for us to access elements on an HTML page.
 
To start, create a new empty folder.
 
Next, download the latest JavaScript browser library from [{{SERVER}}/downloads/phidget22/libraries/any/Phidget22JavaScript.zip here] and copy the files into the folder.
 
Next, create a file called ''index.html'' and copy the following code into it (Note: if you have a newer jQuery, modify the code below to match your version):
 
<syntaxhighlight lang=javascript>
<!DOCTYPE html>
<html>
<head>
    <title>Phidget Manager</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script src="sha256.min.js"></script>
    <script src="phidget22.min.js"></script>
    <script>
        $(document).ready(function() {
            var conn = new phidget22.Connection(8989, 'localhost');
 
            conn.connect().then(function() {
                console.log('connected');
            }).catch(function(err) {
                conn.delete();
                alert('failed to connect to server:' + err);
            });
 
            var man = new phidget22.Manager({
                onDeviceAttach: function(dev) {
                    $('#list').append(new Option(dev.getDeviceName(), dev.getKey()));
                },
                onDeviceDetach: function(dev) {
                    $("#list option[value='" + dev.getKey() + "']").remove();
                }
            });
            man.open();
        });
    </script>
</head>
 
<body>
    <label> Attached Phidgets: </label>
    <div>
        <select multiple id="list" style="width: 500px; height: 200px"></select>
    </div>
</body>
</html>
</syntaxhighlight>
 
This code uses the [[Phidget Manager]] to list any Phidget accessible from your computer (either directly via USB or indirectly over the network).
 
Finally, double click index.html to open it in a browser. You should see something like this:
[[File:Javascript_windows_example.png|link=|center]]
 
Open the developer console to get a better idea what is going on:
[[File:Javascript_windows_devconsole.png|link=|center]]
 
For information about the Node.js examples, keep reading. Otherwise, skip ahead to the [[#Edit the Examples | edit the examples]] section located below.
 
{{Language Page What's Next}}

Revision as of 15:27, 17 October 2019

Language - JavaScript

JavaScript with Browser

Welcome to using Phidgets with JavaScript! By using JavaScript, you will have access to the complete Phidget22 API, including events.

Using JavaScript with a browser provides a good way to create a powerful web interface for your Phidgets programs.

Install Phidget Drivers for JavaScript in Browser

Before getting started with the guides below, ensure you have the following components installed on your machine:

  1. You will need the Phidgets Drivers installed on the server machine
  2. You will need the Phidgets JavaScript Library for Browsers


Version Change

Note: The Phidgets JavaScript library has been bumped to version 2.x.x following a rewrite. The version 2 API is mostly identical to version 1, but does have some breaking changes. It is highly recommended that any code written against version 1 be updated to version 2, as version 1 is considered unstable.

Phidget Network Server

The JavaScript library requires the Phidget Network Server. Start by configuring the server for your OS:

The Phidget Server includes a built-in Webserver. This must be enabled when using the JavaScript library in browser, but can be left disabled when using the library from Node.js.

The Phidget Server Webserver can be used to serve files - such as the Phidget JavaScript library, or your own projects. By default, it serves the JavaScript control panel files. The main purpose of the Webserver is to support a Websockets connection for the Browser library - because regular sockets cannot be used in Browser. The Node.js library uses raw sockets to connect to the Phidget Server, and so does not require the Webserver or Websockets.

JavaScript Control Panel

The JavaScript control panel is a Browser version of our Phidget control panel. This can be used to view and control all Phidgets attached to a Phidget server. The JavaScript control panel is installed by default on Windows, macOS and PhidgetSBC. You can also download the source here.

Make sure the Phidget Server - Webserver is enabled, and running, then navigate to http://localhost:8989. You will now see a program written with JavaScript/HTML that mimics the Phidget Control Panel. It will show all the Phidgets attached to your machine. By double-clicking on the Phidgets, and example will launch.

Javascript windows controlpanel.png

Use Our Examples

One of the best ways to start programming with Phidgets is to use our example code as a guide. Our browser examples are available here.

Write Your Own Code

Let's start by writing a simple HTML page that makes a dynamic list of attached Phidgets visible to the user. We will be using the JavaScript library jQuery in these examples. jQuery is not required in order to use Phidgets, however, it will make it easier for us to access elements on an HTML page.

To start, create a new empty folder.

Next, download the latest JavaScript browser library from here and copy the files into the folder.

Next, create a file called index.html and copy the following code into it (Note: if you have a newer jQuery, modify the code below to match your version):

<!DOCTYPE html>
<html>
<head>
    <title>Phidget Manager</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script src="sha256.min.js"></script>
    <script src="phidget22.min.js"></script>
    <script>
        $(document).ready(function() {
            var conn = new phidget22.Connection(8989, 'localhost');

            conn.connect().then(function() {
                console.log('connected');
            }).catch(function(err) {
                conn.delete();
                alert('failed to connect to server:' + err);
            });

            var man = new phidget22.Manager({
                onDeviceAttach: function(dev) {
                    $('#list').append(new Option(dev.getDeviceName(), dev.getKey()));
                },
                onDeviceDetach: function(dev) {
                    $("#list option[value='" + dev.getKey() + "']").remove();
                }
            });
            man.open();
        });
    </script>
</head>

<body>
    <label> Attached Phidgets: </label>
    <div>
        <select multiple id="list" style="width: 500px; height: 200px"></select>
    </div>
</body>
</html>

This code uses the Phidget Manager to list any Phidget accessible from your computer (either directly via USB or indirectly over the network).

Finally, double click index.html to open it in a browser. You should see something like this:

Javascript windows example.png

Open the developer console to get a better idea what is going on:

Javascript windows devconsole.png

For information about the Node.js examples, keep reading. Otherwise, skip ahead to the edit the examples section located below.

What's Next?

Now that you have set up Phidgets to work with your programming environment, we recommend you read our guide on Phidget Programming Basics to learn the fundamentals of programming with Phidgets.Next Arrow.png