Google Analytics/Google Ads and Content Security Policy - content-security-policy

It's not easy to get Google Analytics/Google Ads working with CSP. I checked out a number of SO articles including this one, but wanted to see if there was another approach.
I found a pretty easy way to do it in this article, and wanted to post it here in case it may be useful to others. I'll post it here as an answer.

I found a pretty easy way to do it in this article:
...move the Google Analytics code snippet to an external code file,
hosted on a domain that is already allowlisted by your script-src
directed, such as the primary domain of your website.
The script originally supplied by Google was:
<!-- Google tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-##########">
</script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-##########');
</script>
I went to https://www.googletagmanager.com/gtag/js?id=UA-##########, downloaded the script, and added this to the bottom of it:
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-##########');
I saved it to my website. I added this:
<script async src="/script-saved-to-my-website.js"></script>
...inside the head section. (Google ads seems to want it inside the head section for some reason).
I added csp policy as described in the above article.
I connected Google Analytics 4 to Google Ads using the "connect to Google ads" feature I found in Google Analytics. Note: you have to have Google Ads in Expert mode, not Smart mode, for this to work.
I set up a Conversion goal on Google Ads.
And... it's working. :) I can see my stats on Google Analytics and my conversions on Google Ads.

Related

How to get challenge key from a target website using geetest captcha

So I am scraping data from a target website using puppeteer.
Target website used geetest captcha, for anti-captcha, I am using 2capcta service,
on their documentation, it's mentioned that we need to get the challenge key every time.
From that the problem begins, target website has embedded the challenge key under
<Iframe>
<Html>
<head>
<script>
when accessing the iframe through DOM elements throw me a CORS error.
I have tried another way also which is available on the scraper box link is below
https://scraperbox.com/blog/solving-a-geetest-slider-captcha-with-puppeteer
it throws me no selector '[aria-label="Click to verify"]' found
it tried the codegrepper way link is below
https://www.codegrepper.com/code-examples/whatever/puppeteer+get+network+requests
throw me on console.error().
Any help would be appreciated to bypass geetest captcha
let me know also if my question is unclear.
Thank you so much for the answer,
so with the response by the above gentleman, the final solution is
when you load your page through puppeteer
await page.waitForSelector('iframe');
this will wait till the time iframe is loaded, now for me the target website has use the iframe with hash link to access it
const elementHandle = await page.$('iframe');
const frame = await elementHandle.contentFrame();
now the frame will have access to your iframe page, so you use the rest same like
await frame.waitForSelector("your selector")

Access denied due to invalid subscription key

I have used the Crossref REST API where I just send it a query in a browser address bar, which then returns results in JSON.
So I send the following URL:
https://api.crossref.org/works?query.bibliographic=Randomized trial of intensive early intervention for children with pervasive developmental disorder&query.author=Groen&rows=1
I was hoping to so the same with the Microsoft REST API, but if I send it:
I get "Access denied due to invalid subscription key".
Can I pass my key via the URL? If so how?
Or is it not that simple.
Does it need other code as well - I can code in PHP if needed, or use jQuery.
Something like:
$(document).ready(function() {
$.ajax({
type:'GET',
url:'https://api.crossref.org/works?query.bibliographic=<?php echo $title ?>&query.author=<?php echo $author ?>&rows=1&select=is-referenced-by-count,author,title,DOI,issn-type,volume,issue,link,page,abstract',
success:function(result) {
var total_results = result.message["total-results"];
}
});
But again, with the Microsoft API - how would I send it the keys?
Thank you.
What is "the Microsoft REST API"? Do you mean Azure API Management? "Invalid subscription key" implies that this is an API hosted in API Management which uses this term to describe its authentication model. The following answer assumes this is the case.
You would need to be registered as a user and be given a subscription key. There is a self-service portal for doing this, which is described by this documentation. It is up to the API's administrator whether you are permitted to self-service or not, so you may or may not be able to do this yourself, or you may have to request the administrator to register you. Further documentation describes a bit how to use the portal.
When you have it, you would apply it as an http header named Ocp-Apim-Subscription-Key, but the name it expects is also configurable and may have been changed, which the administrator would have to tell you.
I finally found the documentation for what I needed (the Microsoft documentation around Azure is a horrendous maze with a lot of stuff that is outdated and broken).
So the documentation is here:
https://msr-apis.portal.azure-api.net/docs/services/academic-search-api/operations/565d753be597ed16ac3ffc03?
I modified the Jacascript example at the bottom of page and came up with:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type:'GET',
url:'https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr=Composite(AA.AuN==%27jaime%20teevan%27)&count=2&attributes=Ti,Y,CC,AA.AuN,AA.AuId',
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","xxxxmykeyxxxxx");
},
success:function(result) {
alert(result.entities[0].Ti);
}
});
});
</script>
</head>
</html>
The query returns all the titles for the author "jamie teevan".
Though in this example I am just outputting the first title via 'alert'. I haven't coded the rest of it yet - just wanted to know if it worked or not at this point.
Now all I need to do is work out the expression to return all the citing documents for a given title + author!! :-/ wish me luck.

How do you integrate Universal Analytics in to Chrome Extensions?

The chrome extension guide has a tutorial for the old analytics install: https://developer.chrome.com/extensions/tut_analytics.html
The instructions just say to link to the https version and update the manifest to allow loading scripts from that URL. So those should still apply to the new version. And in fact I can see the script loading from the server.
Once the script loads analytics does not properly initialize it self and never processes it's internal queue (ga.f) to send those events to the server. There is no error in the console. It's just quietly does nothing.
My guess is that the new Universal Analytics is just not set up to run in the the extension environment but the universal docs make no mention of that: https://developers.google.com/analytics/devguides/collection/analyticsjs/
does anyone know if it's even possible to add Universal Analytics to an extension yet and when that might be added?
There's an issue for that on Google code: The solution is to pass analytics your own protocol check function or simply null for no checking, in an official way.
This has to come after ga('create', ...) :
ga('set', 'checkProtocolTask', null); // Disable file protocol checking.
So you don't need to modify the original analytics.js script. Just include the standard tracking code snippet (dont' forget to add the "https:" prefix) and add "https://www.google-analytics.com" to your Content Security Policy.
A note to ayal gelles' solution:
It is not necessary to add chrome-extension://... to the Content Security Policy since it's already included in the 'self' statement. Also, instead of loading the script via hardcoded URL you should use chrome.runtime.getURL("path/to/analytics.js"). This way you don't need to know your extension's ID, Chrome will fill it in for you.
I wrote up a blog post on this - How to add Google’s Universal Analytics tracking to a Chrome extension
Here's the guts of it:
// Standard Google Universal Analytics code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); // Note: https protocol here
ga('create', 'UA-XXXXX-YY', 'auto');
ga('set', 'checkProtocolTask', function(){});
ga('send', 'pageview', '/options.html');
There are 3 points I’d particularly like to highlight:
Specify “https” at the start of the script address to match with the listing in the manifest.json file
Override checkProtocolTask with an empty function
Send a virtual pageview by specifying the path – /options.html – otherwise Google Analytics will reject a URL in the format chrome-extension://gdocgfhmbfbbbmhnhmmejncjdcbjkhfc/options.html
I just encountered this and seem to have hacked my way through. This might break at some point or not be fully functional, but here goes:
Download the GA uglified+minified source code from here: https://www.google-analytics.com/analytics.js, put in your chrome extension folder, where it could be later loaded by the background page.
In it, find a function that looks something like this:
function Oa(){var a=M[B][E];if("http:"!=a&&"https:"!=a)throw"abort";}.
This is the "point of failure" since our "protocol" is "chrome-extension:" and not either of the two.
So.. change this function to be something like:
function Oa(){var a=M[B][E];if("chrome-extension:"!=a&&"http:"!=a&&"https:"!=a)throw"abort";}
add a "Content Security Policy" of this sort to your manifest file, make sure it points to YOUR LOCAL version of analytics.js you have just modified:
"content_security_policy": "script-src 'self' chrome-extension://EXTENSIONID/path/to/analytics.js; object-src 'self'",
Change the GA snippet to ALSO point to that same file, something like this:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','chrome-extension://EXTENSIONID/path/to/analytics.js','ga');
hope this helps.
I managed to get Google Analytics up and running using Chrome Platform Analytics (CPA). The only confusing part is how to set up a property in the administration console of GA. I had to create a Mobile Application property, which is not too intuitive.
Also, I created an options page that lets users disable analytics if desired, to comply with the opt-out requirements.
I hope that helps!
Regarding new analytics.js (as opposite to old ga.js) this example works for me:
function setupGoogleAnalytics() {
if (!window.ga) {
(function(){
window.ga = function() {
(window.ga.q = window.ga.q || []).push(arguments);
}, window.ga.l = 1 * new Date();
var tag = 'script';
var a = document.createElement(tag);
var m = document.getElementsByTagName(tag)[0];
a.async = 1;
a.src = 'https://www.google-analytics.com/analytics.js';
m.parentNode.insertBefore(a, m);
})();
ga('create', 'UA-XXXXXXX-Y', 'auto');
ga('set', 'checkProtocolTask', null);
}
}
Please note that you need to add following content_security_policy snippet to the manifest.json:
{
...
"content_security_policy": "script-src 'self' https://www.google-analytics.com; object-src 'self'"
...
}
There's a way to use the Measurement Protocol to communicate with Google Analytics.
I have developed a script for that :
https://github.com/melalj/universal-ga-extension

Passing URL of the active tab to my site handler

I suspect this is a total newbie question, but I seem to be missing the basics here. I am NOT new to coding and have a lifetime of experience (27 years) with various languages, but the plugin process is eluding me.
I have developed custom bookmarking system in php & js, it works great and I've been using it for months as I develop it.
I simply want to get the url of the page in the active tab and pass it to my php handler. I want my web site script return the html form into the popup. I can think of a thousand ways that "should" work.
ALL the code examples I am finding seem to over-complicate what should be a simple task.
In short I just want:
<script type="text/javascript">
<!--
var loadurl = "http://my.site.com?theUrl=" + window.location;
location.href = loadurl;
//-->
</script>
And have that page show in the popup. So far I'm at a loss. Even tried ajax calls etc.
Can somebody clue me in on how to achieve this simple task? Maybe I can get started writing extensions with the info.
For the record, most of the examples I have found are deprecated under manifest 2.0
Manifest 2.0 introduces a new feature contentSecurityPolicy. All external resources are blocked by default. For the best practice, you should include all needed asset files in the extension. The communication between your extension and your service (php side) is only data using XHR2.
So, In order to make bookmark extension work, I guess you need to something like this:
Add your service's domain to permissions array
{
...
permissions: ['*://my.site.com/*', 'tabs']
}
Move all javascript from popup.html to popup.js. In popup.js, You create a ajax request to your bookmarking service. More document here
function addBookmark(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://my.site.com/new_bookmark.php?url=" + encodeURIComponent(url), true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
// handle service result here
}
}
xhr.send();
}
chrome.tabs.getSelected(null,function(tab) {
addBookmark(tab.url);
});

Google analytics not gathering data from .asp page

I've installed Google Analytics several times in the past without trouble. However, recently i've installed GA on a .asp page for the first time. Google Analytics dashboard tells me the tag is properly installed, but ever after several days, i can't see any data.
alt text http://img704.imageshack.us/img704/4584/tracking1.jpg
alt text http://img340.imageshack.us/img340/8272/tracking2.jpg
Is there any special setup required for .asp pages or windows servers?
Unfortunately, I don't have the option to install GAHelper.
ASP pages should not require any special configuration. You can check if the tracking code is being outputted correctly by using View Source in your browser, that's all it takes from the server.
The next step would be using Firebug or a similar tool to see if the request to the Analytics servers is going through properly.
Finally got this working by using Google Analytics Asynchronous Tracking, using the following code:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();
</script>
Never quite understood why this didn't work with the usual google tracking code...

Resources