Authentication with easyXDM - easyxdm

I am successfully using easyxdm (with the iframe-intermediate.html methodology) to pull content from a remote server to resize in an iframe on a website, we would now like to lock down our remote content with a username/password, is it possible to re-architect our current implementation to pass a authentication header to allow us to continue to pull the content? we are currently using the below
$(document).ready(function () {
var transport = new easyXDM.Socket({
remote: url,
container: "iframeContainer",
onMessage: function (message, origin) {
message = (Number(message) + 50);
this.container.getElementsByTagName("iframe")[0].style.height = message + "px";
}
});
});

Related

When opening multiple clients, old client does not get updated using nodejs web socket

My goal is when I open a new browser(client), the message sent from the server in the previous client gets updated as well.
Currently,
The clients send messages to the server, the server stores them in localStorage as an array and should send it back to all the clients. All clients should get the same array of messages. It works like ajax call.
As of right now, when I open the first browser, the message is sent to the server and received in the client successfully, and then I open the second one(it works) but the message is not updated in the first browser. PS this acts like a forum, when somebody posts a messages to server, all users should be able to see it.
Here's my code for server:
<html>
<head>
<!-- This is the websocket SERVER -->
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
</head>
<body>
<div id="msg"></div>
<script>
// connect to WEBSOCKET server
var socket = io.connect('http://localhost:5000',{'forceNew':true} );
// Fire an event (that the server will handle
socket.emit('myEvent', 'Hello Message from the client');
// Attach event handler for event fired by server
socket.on('server', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML += "<br>" + data; // append data that we got back
});
</script>
</body>
</html>
Here's for client:
//---------------------------------------------------------------
// The purpose is to introduce you to websockets
// This is a SERVER that is SEPARATE from the http server.
//
// Your webpage (in this case the index.html in this directory)
// will be SERVED by the http server. THEN, it will connect to the
// websocket server. Then - they will talk to each other!
//
// Note that in regular http - the server cannot initiate a conversation
// Here, the websocket server sends a message to the client browser.
//
// This example has THREE parts
// 1) The http server code (which is same as what we did earlier)
// 2) This code - this is the web socket server
// It prints what it got from client. It also sends a message to the
// client after every 1 second.
// 3) The html or client code. Note how it connects to the websocket
// and how it sends and receives messages
//
// To RUN THIS EXAMPLE
// First, run node httpServer.js on one terminal
// Next, run node 1_ws.js on another terminal
// Next, type localhost:4000/index.html on some browser
//
//---------------------------------------------------------------
var items=[];
var io = require('socket.io').listen(5000);
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
}
io.sockets.on('connection', function(socket) {
socket.on('myEvent', function(content) {
//i need to store the content
items.push(content);
localStorage.setItem("list",JSON.stringify(items));
socket.emit('server', JSON.parse(localStorage.getItem("list")));
});
});
I'm running on the local server:( you can ignore the local server if you want, the above code can function on their own)
//---------------------------------------------------------------
// The purpose is to serve a file!
//---------------------------------------------------------------
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var server = http.createServer();
// attach handler
server.on('request', function (req,res) {
var file = path.normalize('.' + req.url);
fs.exists(file, function(exists) {
if (exists) {
var rs = fs.createReadStream(file);
rs.on('error', function() {
res.writeHead(500); // error status
res.end('Internal Server Error');
});
res.writeHead(200); // ok status
// PIPE the read stream with the RESPONSE stream
rs.pipe(res);
}
else {
res.writeHead(404); // error status
res.end('NOT FOUND');
}
});
}); // end server on handler
server.listen(4000);
console.log("start");
You are sending response to only client who sent message to sever only,
To send to all clients which are connected you must use this,
io.emit('server', JSON.parse(localStorage.getItem("list")));
Visit this answer for all
Responses

How to send information from window to the devtool in chrome extension

In my app I have a namespaced application and there's information or metadata myApp carries on it that might be useful to devpane.
window.myApp = new App();
How can I relay or send the following information to the devtool.js?
window.myApp.metadata; // information
And can I send a request from the devtool with a function that customizes the serialization of that metadata?
I've seen similar posts with the solution below, which returns null when I tried it.
chrome.devtools.inspectedWindow.eval("window.myApp", {
useContentScriptContext: true
})
NOTE: If a sample template can be provided that would be wonderful.
This is how I've solved this. It feels more complicated than necessary, but it does work.
In the context of the inspected window
Based on this question.
This is where you've got access to window.myApp.metadata and can put it into the data object.
var event = new CustomEvent("RebroadcastExtensionMessage", {data: ""});
window.dispatchEvent(event);
In the content script
This just forwards the data to the background page.
window.addEventListener("RebroadcastExtensionMessage", function(evt) {
chrome.runtime.sendMessage(evt)
}, false);
In the background page
Based on the Chrome docs.
chrome.runtime.onConnect.addListener(function(devToolsConnection) {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
devToolsConnection.postMessage(request)
});
})
In devtools.js
var backgroundPageConnection = chrome.runtime.connect({
name: "devtools-page"
});
backgroundPageConnection.onMessage.addListener(function (message) {
// Data has arrived in devtools page!!
});

Offline Ready using Service worker

I built an offline first app using the appcache a while ago and wanted to convert it to using the service-worker (my clients all use the latest chrome so I don't have any browser compatibility issues).
I'm using sw-precache to generate a service-worker that caches my local assets (specifically, my html/css/fonts and also some js) and it looks like when the service-worker installs, it does successfully add all the assets to cache storage and it does successfully start (install and activate both fire and complete successfully. And I have the self.skipWaiting() at the end of the install event to start the service-worker (which it does successfully as well)).
The issue is that the "fetch" event doesn't seem to ever fire. As such, if I go offline or open a browser (while already offline) and navigate to the site, I get the Chrome offline dinosaur. When I look at the network tab, it looks like the browser is trying to hit a server to retrieve the pages. I'm not sure what I'm doing wrong and I didn't touch the fetch method that was generated by the sw-precache utility...so I'm not sure what I'm missing. Any help would be greatly appreciated. My fetch event is below:
self.addEventListener('fetch', function(event) {
if (event.request.method === 'GET') {
var urlWithoutIgnoredParameters = stripIgnoredUrlParameters(event.request.url,
IgnoreUrlParametersMatching);
var cacheName = AbsoluteUrlToCacheName[urlWithoutIgnoredParameters];
var directoryIndex = 'index.html';
if (!cacheName && directoryIndex) {
urlWithoutIgnoredParameters = addDirectoryIndex(urlWithoutIgnoredParameters, directoryIndex);
cacheName = AbsoluteUrlToCacheName[urlWithoutIgnoredParameters];
}
var navigateFallback = '';
// Ideally, this would check for event.request.mode === 'navigate', but that is not widely
// supported yet:
// https://code.google.com/p/chromium/issues/detail?id=540967
// https://bugzilla.mozilla.org/show_bug.cgi?id=1209081
if (!cacheName && navigateFallback && event.request.headers.has('accept') &&
event.request.headers.get('accept').includes('text/html') &&
/* eslint-disable quotes, comma-spacing */
isPathWhitelisted([], event.request.url)) {
/* eslint-enable quotes, comma-spacing */
var navigateFallbackUrl = new URL(navigateFallback, self.location);
cacheName = AbsoluteUrlToCacheName[navigateFallbackUrl.toString()];
}
if (cacheName) {
event.respondWith(
// Rely on the fact that each cache we manage should only have one entry, and return that.
caches.open(cacheName).then(function(cache) {
return cache.keys().then(function(keys) {
return cache.match(keys[0]).then(function(response) {
if (response) {
return response;
}
// If for some reason the response was deleted from the cache,
// raise and exception and fall back to the fetch() triggered in the catch().
throw Error('The cache ' + cacheName + ' is empty.');
});
});
}).catch(function(e) {
console.warn('Couldn\'t serve response for "%s" from cache: %O', event.request.url, e);
return fetch(event.request);
})
);
}
}
});

Real time visualization from Remote System (OutSide LAN)

I want to visualize the real time sensor data(Streaming data).For that i used, node.js, html and mysql. Mysql used to store real time sensor data, index.html implements google chart that doPoll app.js file, app.js file provides connection to mysql. I am able to visualize the data from the same system but when i entered url(Public IP) Chrome display "Failed to loadre source : net : : ERR_CONNECTION_REFUSED" and firefox display "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8686/temperatureData. (Reason: CORS request failed)." I have forwarded port 8686 from Router.But i am able to view data in json format using both browser from remote system.Code for app.js is as below:
/**
*
*/
var http = require('http');
var fs = require('fs');
var port = 8686;
var i=0;
var j=0;
function randomInt(low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
// 404 response
function send404Response(response){
response.writeHead(404,{"Content-Type": "text/plain" });
response.write("Error 404: Page not found");
response.end();
}
// handle the user request..
http.createServer(function(req, res) {
console.log('New incoming client request for ' + req.url);
res.writeHeader(200, {
'Content-Type' : 'application/json'
});
switch (req.url) {
case '/temperatureData':
var mysql=require('mysql');
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'feedback',
port:3306
});
var query=connection.query(
// make sure with table name
'SELECT * FROM DEMO2',function(err,result,fields){
if(err) throw err;
//res.write('{"value" :' + result[i].tempvalue + ',"value1":' + result[i].value + '}');
// make sure with tabel fieldname (ex-tempvalue) ok
// side by side open mysql
res.write('{"value" :' + result[i].tempvalue + '}');
//res.write('{"value1":' + result[i].value + '}');
console.log('Temperature:', result[i].tempvalue );
i++;
res.end();
connection.end();
});
break;
case '/temperature':
res.writeHead(200, 'text/html');
var fileStream = fs.createReadStream('index.html');
fileStream.pipe(res);
break;
default:
send404Response(res);
}
}).listen(port);
console.log('Server listening on http://localhost:' + port);
Code for Index.html file shown below:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}">
</script>
</head>
<body>
<div id="chart" style="width: 1500px; height: 700px"></div>
<script>
$(document).ready(function () {
var maxDataPoints = 10;
var chart = new google.visualization.LineChart($('#chart')[0]);
var data = google.visualization.arrayToDataTable([
['Time', 'Temperature'],
[getTime(), 0]
]);
var options = {
title: 'Temperature',
hAxis: {title: 'Time', titleTextStyle: {color: '#333'}}, //Added hAxis and vAxis label
vAxis: {title: 'TempValue', minValue: 0, titleTextStyle: {color: '#333'}},
curveType: 'function',
animation: {
duration: 1000,
easing: 'in'
},
legend: {position: 'bottom'}
};
function addDataPoint(dataPoint) {
if (data.getNumberOfRows() > maxDataPoints) {
data.removeRow(0);
}
data.addRow([getTime(), dataPoint.value]);
chart.draw(data, options);
}
function getTime() {
var d = new Date();
return d.toLocaleTimeString();
}
function doPoll() {
$.getJSON('http://localhost:8686/temperatureData',
function (result) {
addDataPoint(result);
setTimeout(doPoll, 10000);
});
}
doPoll();
});
</script>
</body>
</html>
What Should i do so that i can provide remotely visualization ? I want to provide remotely visualization in mobile and desktop/laptop browser.
Saurabh Just Follow Bellow Steps:
1) On the computer that is running the Microsoft Dynamics NAV Web Server components, on the Start menu, choose Control Panel, choose System and Security, and then choose Windows Firewall.
2) In the navigation pane, choose Advanced settings.
3) In the Windows Firewall with Advanced Settings window, in the navigation pane, choose Inbound Rules, and then in the Actions pane, choose New Rule.
4) On the Rule Type page, choose Port, and then choose the Next button.
5) On the Protocol and Ports page, choose Specific local ports, and then enter the port number. For example, enter 8080 for the default port of the Microsoft Dynamics NAV Web client.Choose the Next button.
6) On the Action page, choose Allow the connection, and then choose the Next button.
7)On the Profile page, choose the profiles, and then choose the Next button.
8) On the Name page, type a name for the rule, and then choose the Finish button.
Once you are done with above steps do port forwarding thorough your router.
Enjoy
CORS on ExpressJS
In your ExpressJS app on node.js, do the following with your routes:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});

Send a message from client to server

I have a server I wrote in NodeJs which listens to port 1234.
From my client (html) I want to send request to my server and wait for an answer.
I tried to use XMLHttpRequest:
var http = new XMLHttpRequest();
var url = "127.0.0.1:1234";
var params = "token=22";
http.open("post", url, true);//"https://www.google.com/search?q=asd"
http.setRequestHeader("Content-type", "text/html");
http.setRequestHeader("Content-length", 0);
http.setRequestHeader("Connection", "keep-alive");
http.onreadystatechange = function() {//Call a function when the state changes.
alert(http.responseText);
}
http.ontimeout = function()
{
alert("timeout");
}
http.timeout=10;
try
{
http.send(null);
}
catch(ex)
{
alert(ex);
}
But I always got exception. The reason was I can't use my own port.
Is There any other way to send request and get respond?
There is nothing wrong with using JQuery.ajax to make your life easier and it does get a lot easier with jquery especially when it comes to XMLHttpRequest.