CertStream Javascript gives error "Uncaught ReferenceError: require is not defined" - javascript
I'm setting up a HTML page that want to use the data from CertStream.
The Javascript library is located at https://github.com/CaliDog/certstream-js
In the install instructions it says " if you're using this in the browser, just add dist/certstream.min.js to a tag, and interact with it as normal!".
I have therefor created a HTML page that uses this tag:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Certstream</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0;"/>
<meta http-equiv="Content-Type" content="text/html; charset=UFT-8" />
</head>
<body>
<h1>CertStream</h1>
<!-- CertStream script -->
<script src="dist/certstream.min.js"></script>
<script>
const CertStreamClient = require('certstream');
let client = new CertStreamClient(function(message){
console.log("Received -> ", message)
});
client.connect();
</script>
<!-- //CertStream script -->
</body>
</html>
But I get the error:
Uncaught ReferenceError: require is not defined
http://localhost/certstream-js/test.html:15
certstream.min.js is located on in the folder "dist":
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.CertStream=t():e.CertStream=t()}(this,function(){return function(e){function t(o){if(n[o])return n[o].exports;var c=n[o]={exports:{},id:o,loaded:!1};return e[o].call(c.exports,c,c.exports,t),c.loaded=!0,c.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=n(1),s=o(i),a=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];c(this,e),this.context={},this.callback=t,this.skipHeartbeats=n}return r(e,[{key:"connect",value:function(){var e=this;console.log("Connecting..."),this.ws=new s.default("wss://certstream.calidog.io/"),console.log("Created ws -> ",this.ws),this.ws.onmessage=function(t){console.log("onmessage called!");var n=JSON.parse(t.data);"heartbeat"===n.message_type&&e.skipHeartbeats||e.callback(t,e.context)},this.ws.onopen=function(){console.log("Connection established to certstream! Waiting for messages...")},this.ws.open()}}]),e}();t.default=a},function(e,t,n){var o,c,r;!function(n,i){c=[],o=i,r="function"==typeof o?o.apply(t,c):o,!(void 0!==r&&(e.exports=r))}(this,function(){function e(t,n,o){function c(e,t){var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!1,!1,t),n}var r={debug:!1,automaticOpen:!0,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1.5,timeoutInterval:2e3,maxReconnectAttempts:null};o||(o={});for(var i in r)"undefined"!=typeof o[i]?this[i]=o[i]:this[i]=r[i];this.url=t,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var s,a=this,u=!1,l=!1,d=document.createElement("div");d.addEventListener("open",function(e){a.onopen(e)}),d.addEventListener("close",function(e){a.onclose(e)}),d.addEventListener("connecting",function(e){a.onconnecting(e)}),d.addEventListener("message",function(e){a.onmessage(e)}),d.addEventListener("error",function(e){a.onerror(e)}),this.addEventListener=d.addEventListener.bind(d),this.removeEventListener=d.removeEventListener.bind(d),this.dispatchEvent=d.dispatchEvent.bind(d),this.open=function(t){if(s=new WebSocket(a.url,n||[]),t){if(this.maxReconnectAttempts&&this.reconnectAttempts>this.maxReconnectAttempts)return}else d.dispatchEvent(c("connecting")),this.reconnectAttempts=0;(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",a.url);var o=s,r=setTimeout(function(){(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",a.url),l=!0,o.close(),l=!1},a.timeoutInterval);s.onopen=function(n){clearTimeout(r),(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onopen",a.url),a.protocol=s.protocol,a.readyState=WebSocket.OPEN,a.reconnectAttempts=0;var o=c("open");o.isReconnect=t,t=!1,d.dispatchEvent(o)},s.onclose=function(n){if(clearTimeout(r),s=null,u)a.readyState=WebSocket.CLOSED,d.dispatchEvent(c("close"));else{a.readyState=WebSocket.CONNECTING;var o=c("connecting");o.code=n.code,o.reason=n.reason,o.wasClean=n.wasClean,d.dispatchEvent(o),t||l||((a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onclose",a.url),d.dispatchEvent(c("close")));var r=a.reconnectInterval*Math.pow(a.reconnectDecay,a.reconnectAttempts);setTimeout(function(){a.reconnectAttempts++,a.open(!0)},r>a.maxReconnectInterval?a.maxReconnectInterval:r)}},s.onmessage=function(t){(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",a.url,t.data);var n=c("message");n.data=t.data,d.dispatchEvent(n)},s.onerror=function(t){(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","onerror",a.url,t),d.dispatchEvent(c("error"))}},1==this.automaticOpen&&this.open(!1),this.send=function(t){if(s)return(a.debug||e.debugAll)&&console.debug("ReconnectingWebSocket","send",a.url,t),s.send(t);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(e,t){"undefined"==typeof e&&(e=1e3),u=!0,s&&s.close(e,t)},this.refresh=function(){s&&s.close()}}if("WebSocket"in window)return e.prototype.onopen=function(e){},e.prototype.onclose=function(e){},e.prototype.onconnecting=function(e){},e.prototype.onmessage=function(e){},e.prototype.onerror=function(e){},e.debugAll=!1,e.CONNECTING=WebSocket.CONNECTING,e.OPEN=WebSocket.OPEN,e.CLOSING=WebSocket.CLOSING,e.CLOSED=WebSocket.CLOSED,e})}])});
//# sourceMappingURL=certstream.min.js.map
What they mean by
...if you're using this in the browser, just add dist/certstream.min.js to a tag, and interact with it as normal!
...is that you don't need the require call (require is CommonJS, not standard JavaScript, and not provided by default on browsers). If you just include the script file in your page, it defines a global CertStream object with a default property providing the default export of the module. (I suspected this was the case, so I grabbed a copy and tried it.)
The docs could be clearer.๐ In particular, it looks like after including the library in the browser, you have to use CertStream.default rather than CertStreamClient. I'd probably do that by doing this up-front:
const CertStreamClient = CertStream.default;
(It's too bad they don't provide a native JavaScript module [ESM] file in their dist folder.)
I looked up into certstream.js module in the dist folder and it is a UMD module. Basically, a UMD module is a JavaScript file that tries to guess at runtime which module system itโs being used in, and then it acts as that kind of module. So you can load the file in a plain <script>, or you can load it from an AMD module loader, or you can load it as a Node.js module, and it will always do something sensible.
In your code since you have already loaded the module using <script> tag, the global CertStream object can be directly used without requiring the module again.
Related
Uncaught Reference Error , method not defined
I am trying to use a method from a javascript module and i dont understand why i get this error : index.html:5 Uncaught ReferenceError: starts is not defined at window.onload (index.html:5:11) I have 2 js files and a html one and all are in the same folder. connect.js function start(){ console.log("ok"); } main.js import{start} from './connect.js'; export{starts}; function starts(){ start(); console.log("started script"); } Index.html <html> <body> <script type="text/javascript" > window.onload=function(ev){ starts(); }; </script> </body> <script type="module" src="./connect.js"></script> <script type="module" src="./main.js"></script> </html>
If you are trying to use modules from the local filesystem (by directly opening index.html), this is not allowed due to CORS restrictions. See this for more details: javascript modules and CORS If there are no other project requirements regarding the use of modules, you may use the scripts without type="module" and remove import/export statements from main.js. Otherwise, you would need a server.
You have made a spelling mistake in second line of your main.js Use export{start} instead of export{starts}; And also change that in HTML file.
exported classes in compiled wasm class don't appear as functions to javascript in the browser
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> HTML page I created for my WebAssembly module. <script> const importObject = { env: { memory:new WebAssembly.Memory({initial:1,maximum:10}), __memory_base: 0, __table_base: 0, } }; WebAssembly.instantiateStreaming(fetch("x2.wasm"),importObject).then(result => { const value = result.instance.exports._inc(17); console.log(value.toString()); }); </script> </body> </html> The cpp file get compiled into wasm without any warnings. But when the script downloads the wasm module, it does not 'see' the exported functions as functions: Here's the error shown in the browser console: Uncaught (in promise) TypeError: result.instance.exports._inc is not a function What am i missing? side note- emscripten was included in the source cpp file too. #include<emscripten> int inc(int a) { return ++a; } this is the cpp source file. As you will see i just started learning. compiler flags: em++ x2.cpp -s SIDE_MODULE=2 -s EXPORTED_FUNCTIONS=['_inc'] -O1 -o x2.wasm
You may use that method along with ccall for C functions. If you prefer to expose classes in wasm interface you should use Embind for classes
Javascript Modules SyntaxError: Cannot use import statement outside a module
So I am trying to learn modules from a youtube video and I'm following along with him but for some reason my code is the exact same as his and is giving me the error SyntaxError: Cannot use import statement outside a module I'm not sure if its because my directories are wrong? I have it under This PC > Desktop > Javascript > module > js > main.js This is the code from main.js import{double} from './utils.js' console.log(double(5)) I also have a index.html file located in the module folder This is my index.html code. <!DOCTYPE html> <head> <title>JavaScript Modules</title> <meta name="viewport" content="width=device-width, initial scale=1.0"> <meta charset="utf-8"> <link rel="stylesheet" href="/assets/dcode.css"> <link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon"> </head> <body> <h1>JavaScript Modules</h1> <u1> <li>Split up your code into separate components</li> <li>Therefore easier to maintain and organize</li> <li>Supported in major browsers(excl. IE)</li> </u1> <script type="module" src="./js/main.js"></script> </body> I'm trying to import code from my utils.js file which is in the same folder as main.js This is my utils.js code. export function double(n){ return n * 2; } When I run the code on the main.js file is where I'm getting the error: SyntaxError: Cannot use import statement outside a module
You need to run your own webserver. An easy one is to get the Web Server for Chrome. You just run it, point it to your local computer folder, and it will give you a localhost port number where your computer is serving the folder. That way you can access your local folders over HTTP. With the following folder structure: /exports/ user.html importer.js exporter.js Where user.html is the page using the importer.js script, which in turn loads exporter.js, you use the following syntax: user.html -- the type="module" notation is necessary. <script src="importer.js" type="module"></script> importer.js -- the ./ relative notation is obligatory. import { doStuff } from './exporter.js' doStuff() exporter.js -- in a production environment, this is your library or module. function doStuff() { console.log('Do stuff') } export { doStuff } With a local server, the above setup will log Do stuff in the console. Forgetting type="module" results in an Uncaught SyntaxError: Cannot use import statement outside a module, not having a relative URL will result in an Uncaught TypeError: Failed to resolve module specifier "exporter.js". Relative references must start with either "/", "./", or "../", and having the wrong URL results in a 404.
Spring mvc loading JS with Uncaught SyntaxError: Unexpected token <
I'm using Spring boot. I have this structure for a simple test app: What I do in my TestController is to get 2 path variables and load index.html: #Controller public class TestController { #RequestMapping("/{vara}/{varb}") public String index(#PathVariable(value="vara") String vara, #PathVariable(value="varb") String varb) { return"/index.html"; } } and the index.html is empty, clean html page: <!DOCTYPE html> <html> <head> <title>Insert title here</title> </head> <body> TEST </body> </html> so typing localhost:8080/abbas/mirza in my browser and everything looks ok and the html page loads easily. I have 2 js files, test.js and /js/testb.js which both have this line of code inside. var s = {}; Now I add this <script src="/test.js"></script> and everything is still ok and I can view the test.js code, but when I add <script src="/js/testb.js"></script> the page throws an exception Uncaught SyntaxError: Unexpected token < and when I try to open the testb.js file it shows me this if I move testb.js into the webapp itself, it will be loaded with no problem. I'm quite newbie using the Spring mvc and still confused with all the configuration regarding routings and accessing resources. Any idea what I'm doing wrong? Edit:(link to github) https://github.com/arashzz/test22
The #RequestMapping pattern you're using is so broad that the path to your JavaScript file testb.js matches it and thus the index page is served in lieu of your js file causing the syntax error to occur. Controller: #RequestMapping("/{vara}/{varb}") JavaScript Path: /js/testb.js This matches that pattern where vara=js and varb=testb.js Your other JavaScript file is located at /test.js and thus doesn't match the pattern and is served correctly. Solution: Adjust the #RequestMapping pattern to something more narrow such as: #RequestMapping("/placeholder/{vara}/{varb}")
Try <script src="js/testb.js"></script> without /as index.html and js directory are in same directory level
JS Lint for Visual Studio 2010 problems
I have a file with a JS object: function Monitor() { var self = this; ... And I have a file that creates an instance of this and uses it. self.monitor = new Monitor(); The files are included in a cshtml file in order: <script type="text/javascript" src="#Url.Content("~/Scripts/Shared/Monitor.js")"> </script> <script type="text/javascript" src="#Url.Content("~/Scripts/Views/NewMonitor_Index.js")"></script> The problem is I get this error: Warning 1 JS Hint: 'Monitor' is not defined. How do I configure it so that it finds the monitor object?
I don't think if there is an automatic way. Although JSHint could detect other script tags, it is probably more difficult to get the actual path to the file. Anyways, if I know that a certain symbol is definitely available in the context, I add a /*global Monitor*/ at the beginning of the script. If a symbol will be available in every script, I add it to my .jshintrc file in the directory, like { "predef": [ "Monitor" ] } But I don't know if/how this works on Windows.