Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Accessing window object in remote nodejs app

Accessing window object in remote nodejs app


Hi I want to access client side JS code within my Nodejs app which is included remotely. A lot like Google Analytics does.

In the above scenario the included script is nodejs and I want to get someID.

If I point it not at my node app but a static JS file it's fine, but I want to consume it and other variables direct into nodejs.


Problem courtesy of: Bob Mcgraw


You're confusing the client and server sides of things.

The Google analytics code you've quoted all occurs client-side. (It triggers server-side code of some kind at their end, but that's not relevant.)

Your NodeJS code is server-side. You can't have the server code directly call client code, access its variables, and such; nor can you do it the other way around. You have to send information to the server (either by loading resources with identifiers in the URLs, via ajax, using web sockets, etc.) and send information to the client (by responding to ajax and other requests, sending web socket messages, etc.).

So for instance, you can do something almost exactly like what Google analytics does:

(function() {
    var someVariabletoPassToTheServer = "foo";
    var s = document.createElement('script');
    s.src = "//" + encodeURIComponent(someVariabletoPassToTheServer);

Your NodeJS code can then process requests to /your/script on your server, receive the data GET parameter, and do something with it. (Which is what Google analytics does, but somewhat more indirectly than the above.)

Solution courtesy of: T.J. Crowder


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Accessing window object in remote nodejs app


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription