What technologies behind Web Push? - web

I was wondering what kind of technologies are behind Web Push, for example https://goroost.com
How is that working? How to configure my server for Web Push? What should I look at?

The underlying technology is the Push API, combined with the Notifications API
You can read more about how to implement this yourself in Google's developer docs. Note that currently push notifications are only supported in Google Chrome, but Microsoft and Mozilla have said they will be implementing it soon.

I can answer for WonderPush.com
First, you need to sign up on WonderPush and declare your website.
Then, Copy/paste the following snippet before the closing <body> tag:
<script>
(function(w, d, s, id, n){
w[n] = w[n] || {q: [],
init: function(o) {w[n].initOpts = o;},
ready: function(c) {w[n].q.push(c);}};
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js";
fjs.parentNode.insertBefore(js, fjs);
}(window, document, 'script', 'wonderpush-jssdk-loader','WonderPush'));
WonderPush.init({
webKey: "[YOUR_WEBKEY]" // sign up for FREE to retrieve your web key
});
</script>

Related

Route Node components to React app button to manage Azure blobs

All,
I am new to React and Node and I am trying to create a react app to manage Azure blob storage and found Microsoft documentation really helpful.
https://learn.microsoft.com/en-us/azure/storage/blobs/quickstart-blobs-javascript-browser
This documentation helps to build what I want in node but I can't figure out how to import these functionalities to React to include them in my UI. For example I want to create a button in react that list blobs, this functionality can be achieved in node with the following code:
const listFiles = async () => {
fileList.size = 0;
fileList.innerHTML = "";
try {
reportStatus("Retrieving file list...");
let iter = containerClient.listBlobsFlat();
let blobItem = await iter.next();
while (!blobItem.done) {
fileList.size += 1;
fileList.innerHTML += `<option>${blobItem.value.name}</option>`;
blobItem = await iter.next();
}
if (fileList.size > 0) {
reportStatus("Done.");
} else {
reportStatus("The container does not contain any files.");
}
} catch (error) {
reportStatus(error.message);
}
};
listButton.addEventListener("click", listFiles);
//Declare the field for UI element
const listButton = document.getElementById("list-button");
Now how I could link this functionality into a button in react, I tried in vain something like:
<button id="list-button">List files</button>
Could you help me to solve this or point me to a source where I can learn more about how to solve similar issues and best practices to connect frontend and backend.
A beginner friendly starting point, if you are new to react is reactjs official tutorial. Here you will learn the basics of building a reactjs application. You can then proceed to learn more on the reactjs docs, especially lists and keys for your case. Then you can learn how to call APIs AJAX and APIs. There are tons of resources out there, which can confuse you if you are getting started, skicking to one source until you are comfortable to check other resources can work wonders.

Facebook Messenger Extensions Javascript Error 2071011

I am trying to use Facebook Messenger Extensions on my bot
but after I've added attached html & javascript code, I receive error 2071011 (I tried this on Android phone).
<!DOCTYPE HTML>
<head>
</head>
<body>
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.com/en_US/messenger.Extensions.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'Messenger'));
window.extAsyncInit = function () {
// the Messenger Extensions JS SDK is done loading
MessengerExtensions.getUserID(function success(uids) {
var psid = uids.psid;
alert(psid);
}, function error(err) {
alert("Messenger Extension Error: " + err);
});
};
</script>
<h2>Test</h2>
</body>
In "messenger.Extensions.js" SDK file I found the following explanation for the error:
"JavaScript bridge does not exist - Please make sure you are in latest
version of Facebook or Messenger App."
What does that mean someone can explain what is the problem?
I had the same problem. I fixed it by:
Make sure you have the latest version of messenger
Make sure your webview is opened with messenger_extensions: true
Make sure you whitelist your domains :https://developers.facebook.com/docs/messenger-platform/thread-settings/domain-whitelisting

Call RESTful WebAPI from a Chrome Web App

I am working on a Chrome Web App. It interacts with Google Cloud Messaging. My question is can the Chrome Web App html5 pages call a RESTful WebAPI service? I am not finding any examples on how to do this inside the app pages? The WebAPI will return JSON. Any tips - very much appreciated.
Edit:
This is in the html page:
<body>
<select id="ParametersDropDownList"></select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="test.js"></script>
</body>
And this is in my test.js file:
var uri = 'http://localhost/custom.webapi/api/parameter?emailaddress=john#foo.bar';
var msg;
$.getJSON(uri)
.done(function(data) {
var appenddata;
$.each(data, function(key, item) {
appenddata += "<option value = '" + item.ParameterName + " '>" + item.ParameterName + " </option>";
});
$('#ParametersDropDownList').html(appenddata);
})
.fail(function(jqXHR, textStatus, err) {
var error = $.parseJSON(jqXHR.responseText);
msg = "Failed to get action data Error message is " + error.message;
});
This code works in a regular html5 page. Meaning, the webapi returns json and the dropdown list is populated with the expected values.
Turned out it was CSP related. Specifically accessing jquery from googleapis.com. I instead downloaded the minified version and added it to the project.

How to track usage on a node.js RESTful service with Google Analytics?

I've written a RESTful node.js service as a backend for http://www.cross-copy.net and would like to not only track usage of the web-client but also other clients (like commandline or Apps) which use the service for inter-device copy/paste. Is it possible to embed the Google Analytics JavaScript API into a node.js application and do server-side tracking?
Since all of the answers are really old, I will mention a new npm package:
https://www.npmjs.com/package/universal-analytics
It's really great and incredible easy to use.
Install universal analytics
npm install universal-analytics --save
In your routes file, require the module. (Replace process.env.GA_ACCOUNT with string like 'UA-12345678-1')
// Init GA client
var ua = require('universal-analytics');
var visitor = ua(process.env.GA_ACCOUNT);
Now inside your endpoint functions, you can track a pageview. (Replace request.url with the current url string like '/api/users/1')
// Track pageview
visitor.pageview(request.url).send();
Read the documentation on UA for more info on this module.
As Brad rightfully sad, there was nothing for Node... So I wrote a nodejs module tailored for this these last few days and just published it on NPM: node-ga
The module is still really new (barely trying it in production on a pet project), so don't hesitate to give your input :)
You won't be able to just drop ga.js into your Node project. It has to be loaded in a browser to function correctly.
I don't believe there is anything out there for Node yet (correct me if I'm wrong!), but you should be able to easily adapt the existing PHP classes for doing logging server-side:
https://developers.google.com/analytics/devguides/collection/other/mobileWebsites
You can see how the URL to request the tracking GIF is constructed within ga.php. Translate ga.php to JS and you're set.
$utmGifLocation = "http://www.google-analytics.com/__utm.gif";
// Construct the gif hit url.
$utmUrl = $utmGifLocation . "?" .
"utmwv=" . VERSION .
"&utmn=" . getRandomNumber() .
"&utmhn=" . urlencode($domainName) .
"&utmr=" . urlencode($documentReferer) .
"&utmp=" . urlencode($documentPath) .
"&utmac=" . $account .
"&utmcc=__utma%3D999.999.999.999.999.1%3B" .
"&utmvid=" . $visitorId .
"&utmip=" . getIP($_SERVER["REMOTE_ADDR"]);
I tried out node-ga, but didn't get event tracking to work. nodealytics did the job.
See Core Reporting API Client Libraries & Sample Code (v3).
There is also the following version: Google APIs Client Library for Node.js (alpha).
I wrote a script to query data with Node.js from Googles Analytics Core Reporting API (v3). The script and a detailed setup description is available here.
Here is the script part:
'use strict';
var googleapi = require('googleapis');
var ApiKeyFile = require('mywebsiteGAapi-6116b1dg49a1.json');
var viewID = 'ga:123456700';
var google = getdefaultObj(googleapi);
var Key = getdefaultObj(ApiKeyFile);
function getdefaultObj(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var jwtClient = new google.default.auth.JWT(Key.default.client_email, null, Key.default.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
jwtClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
return;
}
var analytics = google.default.analytics('v3');
queryData(analytics);
});
function queryData(analytics) {
analytics.data.ga.get({
'auth': jwtClient,
'ids': viewID,
'metrics': 'ga:users,ga:pageviews',
'start-date': 'yesterday',
'end-date': 'today',
}, function (err, response) {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(response, null, 4));
});
}

How to use Node.js to build pages that are a mix between static and dynamic content?

All pages on my 5 page site should be output using a Node.js server.
Most of the page content is static. At the bottom of each page, there is a bit of dynamic content.
My node.js code currently looks like:
var http = require('http');
http.createServer(function (request, response) {
console.log('request starting...');
response.writeHead(200, { 'Content-Type': 'text/html' });
var html = '<!DOCTYPE html><html><head><title>My Title</title></head><body>';
html += 'Some more static content';
html += 'Some more static content';
html += 'Some more static content';
html += 'Some dynamic content';
html += '</body></html>';
response.end(html, 'utf-8');
}).listen(38316);
I'm sure there are numerous things wrong about this example. Please enlighten me!
For example:
How can I add static content to the
page without storing it in a string as a variable value with += numerous times?
What is the best practices way to build a small site in Node.js where all pages are a mix between static and dynamic content?
Personally, I'd use a server that has higher level constructs. For instance, take a look at the expressjs framework - http://expressjs.com/
The constructs you'll be interested in from this package are:
Truly static files (assets etc): app.use(express.static(__dirname + '/public'));
A templating language such as jade, mustache, etc:
http://expressjs.com/en/guide/using-template-engines.html
https://github.com/visionmedia/jade/
You'll want to look up 'locals' and 'partials' for embedding small bits of dynamic content in mostly static content
For example in jade:
!!! 5
html(lang="en")
head
title= pageTitle
script(type='text/javascript')
if (foo) {
bar()
}
body
h1 Jade - node template engine
#container
- if (youAreUsingJade)
p You are amazing
- else
p Get on it!
Becomes:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Jade</title>
<script type="text/javascript">
if (foo) {
bar()
}
</script>
</head>
<body>
<h1>Jade - node template engine</h1>
<div id="container">
<p>You are amazing</p>
</div>
</body>
</html>
If you prefer something a little less drastic I would say look at mustache or one of the other engines that looks a bit more like regular-sauce html.
Alternative you can just use jsDOM. This means you have a DOM object you can manipulate on the server to add your dynamic content, then you can just flush the DOM as a HTML file / string
These days the answer is not so straightforward.
If you don't need to be indexed by Google, consider making a single-page application using socket.io and client-side templates such as jQuery Templates. There are even emerging node.js frameworks for this type of architecture, e.g. socketstream.
If you need to be indexed by Google, do you need your dynamic content to be indexed? If yes,
consider using express and server-side templates such as ejs, jade or mustache. Another (discouraged) approach might be to generate XML from JSON on server and use an XSLT front-end.
If you need only static content to be indexed, consider using express on server, but don't generate any dynamic HTML on server. Instead, send your dynamic content in JSON format to client using AJAX or socket.io, and render it using client-side templates such as jQuery Templates.
Don't consider server-side DOM: DOM doesn't scale for complex layouts, you will sink in a sea of selectors and DOM calls. Even client-side developers understood that and implemented client-side templates. A new promising approach is weld library. It offers best of both worlds, but it is not mature yet to be used in production (e.g. simple things like conditional rendering are not supported yet).
One good way is to use a templating engine. You can store the templates as separate files, and the templating engine has the ability to make the content dynamic. Personally I use yajet (http://www.yajet.net/) which is written for the web but works fine with node, and there are numerous template engines for node on npm.
One of the best things I found is to use NodeJS, Express and Mustache...
You can create your HTML pages as you normally would using Mustache syntax for placeholders for your variables {{name}}...
When a user hits your site, express routs the slug to the correct template...
NodeJS get's the file...
NodeJS get's the dataset from a DB...
Run it through Mustache on the server...
Send the completed page to the client...
Here is a scaled back version I wrote on my blog. It's simple but the idea is pretty sound. I use it to quickly deploy pages on my site.
http://devcrapshoot.com/javascript/nodejs-expressjs-and-mustachejs-template-engine
I went this route because I didn't want to learn all of the extra syntax to write a language I already knew (html). It makes more sense and follows more of a true MVC pattern.
First deliver only static HTML files from server to the client. Then use something like AJAX / server.io to serve the dynamic content. IMO Jade is really ugly for writing HTML code and its better to use a template engine.
I did some Google and found some code by this fellow, its good if you are doing it for PoC / learning.
var server = require('./server');
var controller = require("./controller");
var urlResponseHandlers = require("./urlResponseHandlers");
var handle = {};
handle["/"] = urlResponseHandlers.fetch;
handle["/fetch"] = urlResponseHandlers.fetch;
handle["/save"] = urlResponseHandlers.save;
server.start(controller.dispatch, handle);
Here is how the logic for handling URLs is displayed -
var staticHandler = require('./staticHandler');
function dispatch(handler, pathname, req, res) {
console.log("About to dispatch a request for " + pathname);
var content = "Hey " + pathname;
if (typeof handler[pathname] === 'function') {
content += handler[pathname](req);
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(content);
res.end();
} else {
console.log("No request handler found for " + pathname);
staticHandler.handleStatic(pathname, res);
}
}
Here is how static files can be handled -
function handleStatic(pageUrl, response) {
var filename = path.join(process.cwd(), pageUrl);
path.exists(filename, function (exists) {
if (!exists) {
console.log("not exists: " + filename);
response.writeHead(404, {
'Content-Type': 'text/html'
});
response.write('404 Not Found\n');
response.end();
return;
}
//Do not send Content type, browser will pick it up.
response.writeHead(200);
var fileStream = fs.createReadStream(filename);
fileStream.on('end', function () {
response.end();
});
fileStream.pipe(response);
return;
});
}
exports.handleStatic = handleStatic;
I liked the idea. All code copied from this link!
.
A solution have found to this, without using any other modules and or other script is to make the calling script into a module and include it with the function require().
With this solution I can use javascript which ever way I want
What I would do is make an ajax call to a nodejs script (www.example.com/path/script.js)
script.js would need to be built like a module with the exports.functionName=function(){...}
After that include it in your webserver function require(pathToTheScript).functionName(res,req)
You will also need to end the response in the functionName(res,req) by doing res.end();

Resources