Search code examples
phpjavascriptajaxxssanalytics

How to cross script safely (think analytics)


I'm building a sort of analytics platform for fun this weekend and here is my desired effect.

Client: abc.com Server: test.com

User visits http://abc.com/#12345

Client sends Server via javascript id: 12345, and browser information. Server responds with a new id (ex: #23456), which is then pushed onto the current url (pushstate) http://abc.com/#23456

I was thinking of some kind of script that the Client includes from the Server that communicates with the servers backend, but is that not techincally XSS and unsecure? How do analytics people (Google, GetClicky, etc) do it?!

How can I achieve this like analytics sites do so the internet gods don't get mad at me for XSS, while still maintaing security, and ease of implementation. One included source.

I'd love anything you can do to point me in the right direction.


Solution

  • With jsonp. The idea is that the source of a script tag is the code you want to execute:

    <script type="text/javascript" src="http://yoursite.com?id=12345&this=that" />
    

    edit: Yes, you create the script dynamically similar to an ajax response:

    function getResponse(id){
        var scrpt = document.createElement("script");
        scrpt.type="text/javascript";
        scrpt.src = "http://yoursite.com?id="+id;
        document.body.appendChild(scrpt);
    }
    

    Inside your php page:

    <?PHP 
        if(!isset($_GET['id']))die();
        $id = $_GET['id'];
        echo "alert('$id');";
    ?>
    

    Something of the sort, anyway.

    edit: completely forgot, but the point of jsonp is that you pass in a callback function. See here for some php documentation: http://php.net/manual/en/function.json-encode.php