sponge-clientjs
v1.1.0
Published
A simple package that allows you to to run javascript on the client side from the backend in express.
Downloads
15
Readme
Sponge ClientJS
A simple package that allows you to to run javascript on the client side from the backend in express.
Its a very simple package which may be trivial, but I find it helpful as you can execute different scripts on the client side.
Installation
npm i sponge-clientjs
Usage:
const {clientJS, jsSnippets} = require('sponge-clientjs');
clientJS(engine, type, script, response);
Example:
clientJS('ejs', '', `alert('Hello world)`, res);
An example:
server.get('/', (req, res) => {
var text = 'abcwe'
if(typeof(text) === `string`){
clientJS('', '', `alert('This is a string')`, res);
}
res.sendFile(__dirname + '/index.html')
});
Or you can use the jsSnippets:
server.get('/', (req, res) => {
clientJS('', '', jsSnippets.alert('Hello world'), res);
});
However, if you want to use DOM properties such as getElementById().style or .innnerHTML you will need EJS.
Here is an example:
const express = require('express');
const server = express();
const {clientJS, jsSnippets} = require('sponge-clientjs');
server.set('view engine', 'ejs')
let scriptjs;
server.get('/', (req, res) => {
let text = 'sdsd'
if(typeof(text) === 'string'){
scriptjs = clientJS('ejs', '', jsSnippets.document.getElementById('heading1').style('color', 'blue'), res);
}
res.render('index', {'clientjs': scriptjs});
});
//run multiple lines of code:
server.get('/', (req, res) => {
let text = 'sdsd'
if(typeof(text) === 'string') {
scriptjs = clientJS('ejs', '', [
jsSnippets.alert('Hello'),
jsSnippets.document.getElementById('heading1').style('color', 'blue')
], res);
}
res.render('index', {'clientjs': scriptjs});
});
EJS code:
<h1 id="heading1">New text</h1>
<%- clientjs %>
Hope it helps!
License
ISC