Unable to make tracking pixel send data to api - javascript

I'm trying to use this library to implement a tracking pixel.
I'm testing in my localhost machine with Apache.
I have a index.html page at htdocs/openpixel/index.html
with the following content:
<html>
<head>
Test Pixel
</head>
<body>
Test Pixel
<!-- Start Open Pixel Snippet -->
<script>
!function(e,t,n,p,o,i,a,s,c){e[o]||(a=e[o]=function(){a.process?a.process.apply(a,arguments):a.queue.push(arguments)},a.queue=[],a.t=1*new Date,s=t.createElement(n),s.async=1,s.src=p+"?t="+Math.ceil(new Date/i)*i,c=t.getElementsByTagName(n)[0],c.parentNode.insertBefore(s,c))}(window,document,"script","http://127.0.0.1/openpixel/v1/openpixel.js","opix",864e5),opix("init","ID-123"),opix("event","pageload");
</script>
<!-- End Open Pixel Snippet -->
</body>
</html>
This is openpixel.js, where it should send the data to an endpoint
...
window.onload = function () {
var aTags = document.getElementsByTagName('a');
for (var i = 0, l = aTags.length; i < l; i++) {
aTags[i].onclick = function (e) {
if (Url.externalHost(this)) {
Config.externalHost = { link: this.href, time: now() };
}
}.bind(aTags[i]);
}
};
}(window, document, window["opix"], "opix", "http://localhost:3000/pixel_data", 1));
...
I also created an endpoint api in Node.JS to receive this pixel. When I test it with a browser get resquest it is responding.
app.get('/pixel_data', function(req, res) {
console.log(req.query);
});
The problem is when I access pixel.html, the endpoint /pixel_data is logging nothing. I'm trying to understand the problem here.

You're Node.js server is not able to see the query string because it looks like your server is on localhost:3000 and you are sending a request to 127.0.0.1/openpixel/v1/openpixel.js.
Change your pixel tag to request localhost:3000 by changing http://127.0.0.1/openpixel/v1/openpixel.js to http://localhost:3000/pixel_data.

Related

Silence net::ERR_CONNECTION_REFUSED

Connecting to a non-existent web socket server results in loud errors being logged to the console, usually to the tune of ... net::ERR_CONNECTION_REFUSED.
Anyone have an idea for a hackaround to silence this output? XMLHttpRequest won't work since it yields the same verbose error output if the server is not reachable.
The goal here is to test if the server is available, if it is then connect to it, otherwise use a fallback, and to do this without spamming the console with error output.
Chrome itself is emitting these messages, and there is no way to block them. This is a function of how chrome was built; whenever a ResourceFetcher object attempts to fetch a resource, its response is passed back to its context, and if there's an error, the browser prints it to the console - see here.
Similar question can be found here.
If you'd like, you can use a chrome console filter as this question discusses to block these errors in your console, but there is no way to programmatically block the messages.
I don't know why do you want to prevent this error output. I guess you just want to get rid of them when debugging. So I provide a work around here may be just useful for debugging.
Live demo: http://blackmiaool.com/soa/43012334/boot.html
How to use it?
Open the demo page, click the "boot" button, it will open a new tab. Click the "test" button in the new tab and check the result below. If you want to get a positive result, change the url to wss://echo.websocket.org.
Why?
By using post message, we can make browser tabs communicate with each other. So we can move those error output to a tab that we don't concern.
P.S. You can refresh the target page freely without loosing the connection between it and boot page.
P.P.S You can also use storage event to achieve this.
boot.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>boot page</title>
</head>
<body>
<button onclick="boot()">boot</button>
<p>BTW, you can boot the page without the button if you are willing to allow the "pop-up"</p>
<script>
var targetWindow;
function init() {
targetWindow
}
function boot() {
targetWindow = window.open("target.html");
}
boot();
window.addEventListener('message', function(e) {
var msg = e.data;
var {
action,
url,
origin,
} = msg;
if (action === "testUrl") {
let ws = new WebSocket(url);
ws.addEventListener("error", function() {
targetWindow.postMessage({
action: "urlResult",
url,
data: false,
}, origin);
ws.close();
});
ws.addEventListener("open", function() {
targetWindow.postMessage({
action: "urlResult",
url,
data: true,
}, origin);
ws.close();
});
}
});
</script>
</body>
</html>
target.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>target page</title>
</head>
<body>
<h4>input the url you want to test:</h4>
<textarea type="text" id="input" style="width:300px;height:100px;">
</textarea>
<br>
<div>try <span style="color:red">wss://echo.websocket.org</span> for success result(may be slow)</div>
<button onclick="test()">test</button>
<div id="output"></div>
<script>
var origin = location.origin;
var testUrl = origin.replace(/^https?/, "ws") + "/abcdef"; //not available of course
document.querySelector("#input").value = testUrl;
function output(val) {
document.querySelector("#output").textContent = val;
}
function test() {
if (window.opener) {
window.opener.postMessage({
action: "testUrl",
url: document.querySelector("#input").value,
origin,
}, origin);
} else {
alert("opener is not available");
}
}
window.addEventListener('message', function(e) {
var msg = e.data;
if (msg.action === "urlResult") {
output(`test ${msg.url} result: ${msg.data}`);
}
});
</script>
</body>
</html>

DeployR javascript API

I am trying to integrate r to create a very simple web application using DeployR open 8.0.0 on a Ubuntu machine. I am using the following code on the client side:
<html>
<head><script src="./js-client-library-7.4.3/browser/deployr.min.js"></script></head>
<body>
<script>
deployr.configure({cors: true, host: 'http://192.168.0.103:8000'})
var file = document.getElementById('csv-file').files[0]
deployr.auth('testuser','Aniruddha123')
.io('/r/repository/file/upload')
.attach(file, 'defects.csv')
.io('/r/repository/script/execute')
.data({filename: 'forestPredict.R', author: 'testuser', directory: 'root'})
.end(function(result){
ws = result.data.deployr.response.workspace;
var preds = ws.objects[0].value;
var error = ws.objects[1].value;
document.write('<p>'+preds+'</p>'+'ERROR:' error)
})
</script>
</body>
</html>
and the following R code:
.libPaths( c( .libPaths(), "/home/aniruddha/R/x86_64-pc-linux-gnu-library/3.2") )
library(randomForest)
defects = read.csv('defects.csv')
train = defects[is.na(defects$bugs)]
test = defects[!is.na(defects$bugs)]
forestTest = randomForest(bugs~.,train[-1])
preditions = predict(forestTest, test[-1])
test$bugs = round(preditions)
result = rbind(train, test)
trainPreds = predict(forestTest, train[-1])
meanError = mean(abs(train$bugs - trainPreds))
All that I am getting is a button to upload file and thats it...I dont know where I am going wrong...please help.
You can start the log for the deployR and check what actual you are getting using deployr.configure({cors: true, host: 'http://192.168.0.103:8000',logging:true}).
Also, When you click on your upload button, start the developer tools of the browser. You can check where the script is failing.

history.pushState error,i dont know why

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function(){
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');
var iNow = 1;
oInput.onclick = function(){
var number = randomNum(35,7);
oDiv.innerHTML = number;
history.pushState(number,'');
}
window.onpopstate = function(event){
var number = event.state || '';
oDiv.innerHTML = number;
}
function randomNum(alls,now){
var arr = [];
var newArr = [];
for(var i=1;i<=alls;i++){
arr.push(i);
}
for(var i=0;i<now;i++){
newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
}
return newArr;
}
}
</script>
</head>
<body>
<input type="button" id="input1" value="35選7" />
<div id="div1"></div>
</body>
I don't know why history.pushState does not work, it throws the error:
history.html:14 Uncaught SecurityError: Failed to execute 'pushState' on
'History': A history state object with URL
'file:///C:/Users/TED/Documents/HBuilderProjects/javascript-%E7%9F%A5%E8%AD%98%E9%A1%9E/history.html' cannot be created in a document
with origin 'null' and URL
'file:///C:/Users/TED/Documents/HBuilderProjects/javascript-%E7%9F%A5%E8%AD%98%E9%A1%9E/history.html'.oInput.onclick # history.html:14
Don't pretend that file:/// is the same as "web pages": they didn't get loaded by the browser using the same mechanism that real web pages go through, and lots of things that web pages can do will not work for "plain files".
If you want to see how your code behaves as web page, using web APIs, then you'll need to load it properly using http(s). That means using a simple server (not even a full blow Apache or the like, just a one-liner http server like python -m SimpleHTTPServer, or php -S localhost:8000 or node.js's http-server or live-server packages, etc. etc.) and then load it through http://localhost:someport/yourfilename, where "someport" is whatever port number the one-line server says is being used, and "yourfilename" is obviously the name of your file.

Face to face video chat using openTok (tokbox)

I build a kind of a social network where the users can chat with each other.
Only private chats, not rooms or groups or anything like this.
I want to to add a feature to the chat - video chat.
And I find openTok (tokbox).
I read alot from thier manual but I can't make it work.
I started in something simple.
I opend in two different computers url with this code:
<html>
<head>
<script src="http://static.opentok.com/webrtc/v2.0/js/TB.min.js" ></script>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<script type="text/javascript">
var apiKey = **myApiKey**;
var sessionId = **sessionId **;
var token = **token**;
function sessionConnectedHandler (event) {
session.publish( publisher );
subscribeToStreams(event.streams);
}
function subscribeToStreams(streams) {
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
if (stream.connection.connectionId
!= session.connection.connectionId) {
session.subscribe(stream);
}
}
}
function streamCreatedHandler(event) {
subscribeToStreams(event.streams);
}
var publisher = TB.initPublisher(apiKey);
var session = TB.initSession(sessionId);
session.connect(apiKey, token);
session.addEventListener("sessionConnected",
sessionConnectedHandler);
session.addEventListener("streamCreated",
streamCreatedHandler);
</script>
</head>
<body>
</body>
</html>
Of course I changed myApiKey, sessionId, token to my details from my account.
The problem is that In every page I can see myself, buy the partner window doesn't stop loading...
What can I do?
Thanks
In your sessionConnectedHandler(), you have to remove publisher parameter, then it works fine... Somewhat look like this:
function sessionConnectedHandler(event) {
subscribeToStreams(event.streams);
session.publish();
}

Play Framework 2.1 websockets in Chrome

I can't seem to get websocket communication to work in the Play Framework version 2.1.
I created a simple test that does nothing but send messages back and forth with a push of a button. All the code for it is below. But nothing shows up except for the button.
Has anybody seen this problem or can someone tell me what I may be doing wrong in the code below?
I am using the latest version of Chrome.
Here is my simple setup.
In Application.java
public static Result index() {
return ok(index.render());
}
public static WebSocket<String> sockHandler() {
return new WebSocket<String>() {
// called when the websocket is established
public void onReady(WebSocket.In<String> in,
WebSocket.Out<String> out) {
// register a callback for processing instream events
in.onMessage(new Callback<String>() {
public void invoke(String event) {
System.out.println(event);
}
});
// write out a greeting
out.write("I'm contacting you regarding your recent websocket.");
}
};
}
In Routes File
GET / controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
GET /greeter controllers.Application.sockHandler()
In Index.Scala.html
#main(null) {
<div class="greeting"></div>
<button class="send">Send</button>
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var sock = new WS("#routes.Application.sockHandler()")
sock.onmessage = function(event) {
$('.greeting').append(event.data)
}
$('button.send').click(function() {
sock.send("I'm sending a message now.")
});
})
</script>
}
In Main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
The problem is in
var sock = new WS("#routes.Application.sockHandler()")
you have to specify the protocol and the complete url in the format: ws://localhost:9000/greeter.
Check this question to do it in javascript: How to construct a WebSocket URI relative to the page URI?
you can use a Route's webSocketURL() method to retrieve a url that can be passed to a WebSocket's constructor. Here's an example from Play's websocket-chat sample code:
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("#routes.Application.chat(username).webSocketURL()")
var sendMessage = function() {
chatSocket.send(JSON.stringify(
{text: $("#talk").val()}
))
$("#talk").val('')
}
// ...
So in your code you can use something like
var sock = new WS("#routes.Application.sockHandler().webSocketURL()");
Personally I don't like intermingling interpolated code with JS, since I think that any code executing on the client should only be concerned with the state of the client, and not the server (not to mention it makes refactoring the script out into an external file impossible), so I tend to do something like this:
<div class="container app-container"
data-ws-uri="#routes.Application.WSUri.webSocketURL()">
.......
</div>
Then in my JS I can just do something like
var sock = new WS(document.querySelector(".app-container").dataset.wsUri);
// ....

Categories