How can I apply GA download tracking with Sitecore? - google-analytics

I'm posting this question to Stackflow b/c after doing much research into an answer to this very question online, I did not come across a straight forward answer and had to do my own sleuthwork to resolve this.
Basically, Sitecore uses a handler file .ASHX for all files uploaded to the Media Library. Since the 3rd party GA tracking tool I was using (entourage.js or gatags.js) does not recognize .ashx as a whitelisted download file, it was not adding the appropriate GA tracking syntax to the GA pixel tracker (__utm.gif).
So the solution turns out to be simple but sadly, not retroactive, meaning all files previously uploaded to the Media Library in the Sitecore content tree will continue to use the ashx extension unless you reupload the image. In your web.config file, search for the "Media.RequestExtension" setting. If you change the value associated with this setting from "ashx" to a blank string, this will force Sitecore to use the originalextension of the file and image in the Sitecore Media Library.
Aside from interfering with GA analytics, this method of turning every downloadable file extension into an ashx file is poor SEO practice. AND, Sitecore will not point you in the right direction of getting around this other than a round-about way (google Sitecore dynamic linking and configuration) because they want you to use their Sitecore OMS download tracking capability. And that's it! Two days of research led me to this conclusion.

So the solution turns out to be simple but sadly, not retroactive,
meaning all files previously uploaded to the Media Library in the
Sitecore content tree will continue to use the ashx extension unless
you reupload the image.
Not sure where you got this information, but it's incorrect. You can blank out the Media.RequestExtension setting and all existing files will use their original extension. In IIS7 Integrated Mode, you should be able to make this change without having to make other server configuration changes.
Edit: More Info
If you analyze Sitecore.Configuration.Settings.Media.RequestExtension (the API equivalent to this settings) in a decompiler, you can see that it's only used by the MediaProvider when constructing the Media URL. Sitecore should remember the original extension of the media and can serve it with its original URL, regardless of what this setting was when it was uploaded. That's my experience, anyway, and it seems to be validated by looking into Sitecore.Kernel.

You could use this script to track download events via Google Analytics.
if (typeof jQuery != 'undefined') {
jQuery(document).ready(function($) {
var filetypes = /\.(zip|pdf|doc*|xls*|ppt*|jpg|ashx)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
jQuery('a').each(function() {
var href = jQuery(this).attr('href');
if (href) {
if (href.indexOf('?') != '-1') {
href = href.substring(0, href.indexOf('?'));
}
if (href.match(filetypes)) {
jQuery(this).click(function() {
var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
var filePath = String(href);
_gaq.push(['_trackEvent', 'Download', extension, filePath]);
if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function() {
location.href = baseHref + href;
}, 200);
return false;
}
});
}
}
});
});
}
Just add in the required file types here at this line -
var filetypes = /.(zip|pdf|doc*|xls*|ppt*|jpg|ashx)$/i;

Having done a quick google for gatags.js, I can see that you can add an extension to the whitelist on line 24:
var isDoc = path.match(/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/);
Change it to:
var isDoc = path.match(/\.(?:ashx|doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/);
Alternatively, you could attach the Google Analytics _trackEvent yourself with a dom selector and a click event.
Either way, I think OMS can track media library files regardless of extension - removing the default ashx extension doesn't stop the file being handled by Sitecore.

Related

Loading local file inside an iframe in Electron

I've tried different approaches but all are problematic.
So first of all I was using webview, but as per electron documentation, this tag is undergoing major architectural changes and it's recommended to use iframe or other alternatives. Furthermore, the webview tag gives me a warning while used alongside VueJS that the component is not registered. I understand this component doesn't exist within HTML standards and is something specific to electron, so I am not sure how to tell Vue to ignore or recognize it in the use case of an electron app.
Coming to the iframe problem, approach one of loading the file directly via src, gives me the obvious error Not allowed to load local resource:. Turning off webSecurity though allows the file to load but I read it's not recommended to turn it off. I am not sure if there are specific use case where it's safe to turn it off or shouldn't be at all.
I decided to try via file protocol as I already have it in place. The protocol code:
protocol.registerFileProtocol('downloads', (request, callback) => {
const url = request.url.substring('downloads:///'.length)
const location = path.normalize(paths.downloads(url))
callback({ path: location })
})
Though when I load the file this way, the renderer process crash without errors. Is there something in addition to the above which would help loading local files via iframe?
Edit 1
My use case is the following: I have a typical entry point to an index.html which contains code for a VueJS app.
if (app.isPackaged) {
window.loadFile(join(__dirname, '../renderer/index.html'))
} else {
// 🚧 Use ['ENV_NAME'] avoid vite:define plugin
const url = `http://${process.env['VITE_DEV_SERVER_HOST']}:${process.env['VITE_DEV_SERVER_PORT']}`
window.loadURL(url)
window.webContents.openDevTools()
}
Inside that VueJS app, I require to list html files from a directory. I am able to achieve so via webview but I have tried to move away from it for the reason mentioned above. I tried using iframe but encountered issues as well. If there's a setting that doesn't turn off all security and allows me to load the file via iframe, that would be ideal.
This is kind of the reverse of this question where they're using an iframe, running into the "not allowed to load local resource" and being told to use a <webview> instead.
The <webview> docs list BrowserView as another alternative which is what I would recommend here. That should be much easier to work with than an iframe.
const { app, BrowserView, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow()
const view = new BrowserView()
win.setBrowserView(view)
view.setBounds({ x: 0, y: 0, width: 300, height: 300 })
view.webContents.loadFile('<yourFile>')
})
Even though it is not recommended to use webview tag, I decided to go forward as it's the only thing that works for me. The only issue then was this error where Vue does not recognize the tag. To work around that error/warning, I had to update my vite.js config:
plugins: [
vue({
template: {
compilerOptions: {
isCustomElement: (tag) => tag === 'webview'
}
}
}),
// ...

How to add Google Analytics cross-domain linker parameters to an URL with javascript (using GTM)?

On our site, we have a couple of buttons that will take you to a different domain but not before we've composed the actual URL with appropriate query parameters in Javascript. What is the best way to add Google Analytic's linker parameter to this URL? We're using the universal script injected by Google Tag Manager.
Ah... found it. Documentation suggests:
ga(function(tracker) { var linkerParam = tracker.get('linkerParam'); })
But the tracker is undefined in my case.
I found the solution in this blog post:
if (typeof(window["ga"]) !== "undefined") {
var firstTracker = ga.getAll()[0];
if (firstTracker) { return firstTracker.get("linkerParam"); }
}
But... on further investigation, I found the root cause: using GTM means that there are potentially multiple trackers active on a page. Hence the single ga-function won't work. I haven't found the exact GTM-compatible way of doing this, but I'll stick with this workaround for now.

Search customization for html documents in Alfresco

I have a set of html documents. According to the normal search, whenever a document is searched for, a set of relevant documents shows up, by clicking on which we are taken to the document details page. From this document details, we can do view in Browser. My clients want this search results link to take them directly to the View in Browser page, skipping the document details page for html documents. How can I achieve this?
I have a custom JavaScript which creates the html page. Can I modify the JS code, to produce this functionality?
Thanks in advance!
Assuming you are running a recent version of Alfresco, there is a hack and an proper way.
The code you want to tweak is in share/components/search/search.js.
renderCellDescription = function Search_renderCellDescription(elCell, oRecord, oColumn, oData)
{
// ...
// displayname and link to details page
var displayName = oRecord.getData("displayName");
var desc = '<h3 class="itemname">' + $html(displayName) + '';
// ...
}
For the proper way, try following http://blogs.alfresco.com/wp/developer/2012/05/22/customizing-share-javascript-widget-instantiation-part-1/
If this looks all Chinese to you, hack the file in place an keep a copy of the original. Drop the tweaked version in tomcat/shared/classes/components/search.
If you are not running a recent version of Alfresco, go staight for the hack.

Phonegap: InAppBrowser insertCSS file

I'm trying to create an app that loads a website and then adds some custom CSS to adjust it to a mobile device.
I'm using window.open to load the page successfully, and I have a callback on loadstop where I'm calling browser.insertCSS, this is where the problem is.
If I do something like this:
browser.insertCSS({code:"body{background-color:red;}");
The style is applied correctly. However if I do this:
browser.insertCSS({file:"mobile-style.css");
And add the same CSS to the file, it doesn't get loaded
I have tried different paths (putting the file in the www folder, in the css folder, in the same folder as the JS file, and referencing it with "./mobile-style.css", "mobile-style.css", "/www/mobile-style.css", "/mobile-style.css" but none of them seem to load the file correctly.
I saw another post What should file paths fed to insertCSS() be relative to? where this same question was asked, but there is no accepted answer (I have tried the suggestion there and it doesn't work).
Any help would be greatly appreciated.
Thanks
Will
you have to wait until your inAppBrowser page loading finishes.
You must add an event listener:
var inApp = window.open('mypage.html', '_blank', 'location=no');
inApp.addEventListener('loadstop', function(){
inApp.insertCSS({
file: 'inAppStyle.css'
},onSuccess);
});
EDITED
Use this path for your android projects file:///android_asset/{your folder}
INFO: https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md#android-file-system-layout
I couldn't find the right local path. Instead, I just uploaded the css file to the web and provided a regular URL
file: 'http://mywebsite.com/path-if-needed/my.css'
Not ideal to have an external dependency, but not a big deal since InAppBrowser itself requires internet access.
I probably know why it won't work, it is because your path isn't right, this css file should not put in www folder, neither the cordova project folder, u should put it into the server, for example, if ur browser is to visit http://192.168.1.1/admin, then the cordova only fetch this file when the browser is under the 192.168.1.1/admin, it fetch the file under the server directory.I don't know if u use any debug tool , if u use one, it's easy to find out what went wrong, ur console will log the error which path it fetch the css file and didn't get it.
If you want to add an external CSS file stored locally in the APP's sandbox and not around in the Internet, this is the only way, that is, you get the external file, you store it into a string variable, and then you insert such code into the Browser.
var inAppBrowserRef = cordova.InAppBrowser.open(url, "_blank", "location=no");
//when load stops call loadedCallbackFunction
inAppBrowserRef.addEventListener('loadstop', loadedCallbackFunction);
function loadedCallbackFunction() {
console.log("InAppBrowser Window loaded");
$.ajax({
type: "GET",
url: cordova.file.applicationDirectory + "www/css/myExternalCSS.css",
dataType: "text",
success: function (CSScode) {
inAppBrowserRef.insertCSS(
{ code: JScode},
function(){
console.log("CSS code Inserted Succesfully into inApp Browser Window");
});
},
error: function () {
console.error("Ajax Error");
}
});
}
You need the cordova-plugin-inappbrowser

Open PDF in the PhoneGap App that is made in HTML and CSS

I have a strange problem with my iPad App in Phone Gap. The problem is that I have to open PDF document in my app through links and when I click the link which opens the PDF, it shows me the PDF document with no back link.
Hence, when I open the PDF document in my app through a link, it takes me to a dead end and there is no way I can go back to the main page of my app.
My question is that how can I have a Top-Bar, when I open a PDF which could take me back to my home page? Any internal element for the iPad may be?
Thanks a lot.
Try using the In App Browser plugin.
If you're using a later Phonegap / Cordova version (2.8.0, 2.9.0 etc) it should come with it - nothing else to install.
http://docs.phonegap.com/en/2.9.0/cordova_inappbrowser_inappbrowser.md.html#InAppBrowser
It will allow you to open the PDF in the a new 'window' that overlays your app. It has a 'Done' button that users can use to close it and return to your app when they are finished.
You would open the PDF using the In-App Browser, using something like this:
window.open('http://whitelisted-url.com/pdftoopen.pdf', '_blank');
I.e. the _blank option triggers the In-App Browser plugin. If you were to use _system instead it might open it in iBooks (just guessing there - not 100% sure if it would use iBooks).
Try prefixing https://docs.google.com/viewer?url= in the URL
like, window.open('https://docs.google.com/viewer?url=http://www.example.com/example.pdf&embedded=true', '_blank', 'location=yes');
Try this to open any kind of documents from URL using following steps:
install this plugin : cordova plugin add https://github.com/ti8m/DocumentHandler
use this code :
handleDocumentWithURL(function() { console.log('success'); }, function(error) { console.log('failure'); if (error == 53) { console.log('No app that handles this file type.'); } }, 'http://www.example.com/path/to/document.pdf');
It works for me both on Android and IOS. I used it for open images and PDF files.
Android : It opens files using system apps if available, otherwise it give an error, which you can handle.
IOS : It opens files in popup like view with Done button and Option button.
It doesn't show your docs URL.
Source is available here : https://github.com/ti8m/DocumentHandler
Thanks asgeo1,
I solved it by using window.open().
<img src="images/samplens.jpg" border="0" />
Hope it helps.
I've ended up using WebIntent
as described here. The tricky part was to modify WebIntent.java to properly identify file type:
String type = obj.has("type") ? obj.getString("type") : null;
// New code starts
Uri uri = obj.has("url") ? Uri.parse(obj.getString("url")) : null;
String extension = MimeTypeMap.getFileExtensionFromUrl(obj.getString("url"));
if(extension != null){
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
type = mimeTypeMap.getMimeTypeFromExtension(extension);
}
// New code ends
JSONObject extras = obj.has("extras") ? obj.getJSONObject("extras") : null;

Resources