Skip to content

Commit

Permalink
Inject the tracking script under head tag
Browse files Browse the repository at this point in the history
  • Loading branch information
msufa committed Dec 9, 2016
1 parent fb50df2 commit c7e8517
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
2 changes: 1 addition & 1 deletion test/test.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta charset="utf-8"/>
<title>Test page</title>
</head>
<body>
Expand Down
25 changes: 20 additions & 5 deletions tracking-id-injector.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
#!/usr/bin/python

import sys
from bs4 import BeautifulSoup

if len(sys.argv) < 3:
print('usage: python {} input_filename output_filename'.format(sys.argv[0]))
TRACKING_SCRIPT_TEMPLATE = """
(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');
ga('create', '{0}', 'auto');
ga('send', 'pageview');
"""

if len(sys.argv) < 4:
print('usage: python {0} tracking_id input_filename output_filename'.format(sys.argv[0]))
exit(1)

with open(sys.argv[1], 'r') as infile:
with open(sys.argv[2], 'w') as outfile:
outfile.write(infile.read())
with open(sys.argv[2], 'r') as infile:
soup = BeautifulSoup(infile, "html.parser")
tracking_script = soup.new_tag("script")
tracking_script.string = TRACKING_SCRIPT_TEMPLATE.format(sys.argv[1])
soup.head.append(tracking_script)

with open(sys.argv[3], 'w') as outfile:
outfile.write(soup.prettify())

0 comments on commit c7e8517

Please sign in to comment.