Here's one method of getting web3 working in an HTML file.
- Get web3.js from here. web3.min.js will also work, but it'll have less detail for debugging.
- In the same directory as web3.js, create an HTML file including web3.js, and also set the provider.
Here's an example:
<html>
<script src="web3.js"></script>
<script>
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
</script>
</html>
- Start testrpc in a terminal.
- Open that HTML file in any browser.
- In that one HTML file, you can now access web3. To test this, you can open the browser's console (it's CTRL-SHIFT-K in Firefox) and type
web3.isConnected()
. If it says true
, you're good to go.
That's right, you don't actually need mist. In fact, I recommend using an ordinary browser such as Firefox so that you can use common debugging tools such as Firebug. Just for now, you can use the browser's console as a REPL (Read, Evaluate, Print Loop) (a.k.a. a command line) to mess around. If you include any javascript in this HTML file, it'll have access to web3.
The caveat with my example is that this will overwrite whatever web3 the browser already has. Here's the code for it to not do that (replace the contents of the second script tag):
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
But try the simpler code first, since I've found it's better to get something working first, then get it right.
Similarly, this is the simplest method, but there's much better methods of including javascript libraries. I personally use tools such as browserify and beefy to handle dependencies (such as web3.)