Bob Mcgraw
Bob Mcgraw

Reputation: 3

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.

<script type="text/javascript">
    var someID = 123456;
    (function() {
      var zx = document.createElement('script'); zx.type = 'text/javascript'; zx.async = true;
      zx.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'example.com/';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(zx, s);
    })();
</script>

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.

Thanks

Upvotes: 0

Views: 2134

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

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 = "//example.com/your/script?data=" + encodeURIComponent(someVariabletoPassToTheServer);
    document.getElementsByTagName('script')[0].parentNode.appendChild(s);
})();

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

Upvotes: 4

Related Questions