I've created a script similar to Google Analytics (creates a script on load, pushes data to an array, gets used in the hosted script to store tracking data in a database) for use in Facebook's Instant Article so I can track stats internally on my software. But the problem is that Facebook gives a CSP errors about my script:
Refused to load the script 'https://My-Domain.com/js/w_analytics.js'
because it violates the following Content Security Policy directive:
"script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com
*.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:*
'unsafe-inline' 'unsafe-eval' fbstatic-a.akamaihd.net
fbcdn-static-b-a.akamaihd.net *.atlassolutions.com blob: data: 'self'".
The Instant Article markup is all correct with the script inside the expected block of code:
<figure class="op-tracker">
<iframe> [code] </iframe>
</figure>
I'm currently debugging this via Facebook's debug page: http://ww.ia-tracker.fbsbx.com/instant_article_test?url=<share_url>
The strange thing is that occasionally I do get some stats through to my database from the Instant Article, but just not consistently or on each page view.
Facebook docs say you can do a direct URL to your tracker, like so:
<figure class="op-tracker">
<iframe src="http://my-url-tracker.com/">
<!--
The request to http://my-url-tracker.com/ will be rewritten to
include the following query parameters:
ia_share_url: The URL the user shared
ia_title: The article title
-->
</iframe>
</figure>
But the problem is that it says it only sends those two parameters, when my own tracker takes more info which is required for my software (such as the UA string), so ideally I'd like to avoid this approach.
Has anyone else had any experience using custom tracking scripts for this?
After messing around on this for days, I got it to work by using the op-tracker
with a iframe src
to my custom tracking script, like so:
<figure class="op-tracker">
<iframe src="http://my-url.com/tracker.php"></iframe>
</figure>
The Facebook docs don't give much away about this method, and they omit a small bit of info: there is a third parameter sent which is the referrer ia_referrer
(this returns as ia.facebook.com
)
You can then use a combination of $_GET
and $_SERVER
on your "tracker.php" script to grab whatever other details you need for your script, eg:
$instantArticleURL = urldecode($_GET['ia_share_url']);
$HTTPreferrer = $_GET['ia_referrer'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$visitorIP = $_SERVER['REMOTE_ADDR'];
You may also need to include this header()
in your tracker.php to make sure that Facebook can access the script (modify it to suit your site needs, obviously):
header("Access-Control-Allow-Origin: https://www.facebook.com");
Hopefully this will save someone else a few days of headaches :)