Skip to content

Commit

Permalink
Add Google Analytics to incore documentation (#400)
Browse files Browse the repository at this point in the history
* added python script to insert header

* modified python script path in Dockerfile

* updated changelog
  • Loading branch information
ywkim312 authored Jun 4, 2024
1 parent 3820c12 commit b7c4f76
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Gas facility damage analysis documentation and example notebook [#387](https://github.com/IN-CORE/incore-docs/issues/387)
- Traffic flow recovery analysis documentation and example notebook [#389](https://github.com/IN-CORE/incore-docs/issues/389)
- Social vulnerability score analysis documentation and example notebook [#392](https://github.com/IN-CORE/incore-docs/issues/392)
- Google Analytics to the main documentation [#399](https://github.com/IN-CORE/incore-docs/issues/399)
- Google Analytics to the api sphinx documentation [#396](https://github.com/IN-CORE/incore-docs/issues/396)

## [4.11.0] - 2024-04-30
Expand Down
8 changes: 8 additions & 0 deletions manual_jb/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,17 @@ RUN apt-get -y update

WORKDIR /src
COPY requirements.txt /src/
COPY insert_ga_to_header.py /src/
RUN python3 -m pip install -r requirements.txt


COPY content/ /src/content/
RUN jupyter-book build content/

# Run the insert_ga_to_header.py script to insert Google Analytics code
RUN python3 -m pip install beautifulsoup4
RUN python3 insert_ga_to_header.py

# ----------------------------------------------------------------------
# Building actual container
# ----------------------------------------------------------------------
Expand All @@ -22,3 +28,5 @@ FROM nginx
RUN mkdir -p /usr/share/nginx/html/doc/incore
COPY --from=builder /src/content/_build/html/ /usr/share/nginx/html/doc/incore/

COPY config /usr/share/nginx/html/doc/incore/config

3 changes: 3 additions & 0 deletions manual_jb/config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"GA_KEY": "Test-Google-Analytics-Key-Replace-Me"
}
31 changes: 31 additions & 0 deletions manual_jb/config/googleAnalytics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// analytics.js
(function() {
// Fetch the runtime configuration
fetch('config/config.json')
.then(response => {
if (!response.ok) {
throw new Error('Configuration file not found');
}
return response.json();
})
.then(config => {
if (!config.GA_KEY) {
throw new Error('GA_KEY is missing in the configuration');
}

// Create the script tag for Google Tag Manager
const scriptTag = document.createElement('script');
scriptTag.async = true;
scriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${config.GA_KEY}`;
document.head.appendChild(scriptTag);

// Initialize Google Analytics
window.dataLayer = window.dataLayer || [];

function gtag() { dataLayer.push(arguments); }

gtag('js', new Date());
gtag('config', config.GA_KEY);
})
.catch(error => console.warn('GA setup skipped:', error.message));
})();
46 changes: 46 additions & 0 deletions manual_jb/insert_ga_to_header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import os
from bs4 import BeautifulSoup

# Directory containing the built HTML files
build_dir = "content/_build/html"

# Google Analytics code snippet to insert into the HTML files
ga_code = f"""
<script>
// Fetch and execute the analytics script
fetch('config/googleAnalytics.js')
.then(response => response.text())
.then(scriptContent => {{
const scriptTag = document.createElement('script');
scriptTag.textContent = scriptContent;
document.head.appendChild(scriptTag);
}})
.catch(error => console.error('Failed to load analytics script:', error));
</script>
"""

# Loop through each HTML file in the build directory
for filename in os.listdir(build_dir):
if filename.endswith(".html"):
filepath = os.path.join(build_dir, filename)
print(f"Processing file: {filepath}")

# Read the content of the HTML file
with open(filepath, "r", encoding="utf-8") as file:
html_content = file.read()

# Parse HTML content using BeautifulSoup
soup = BeautifulSoup(html_content, "html.parser")

# Find the <head> tag and insert the Google Analytics code before it
head_tag = soup.find("head")
if head_tag:
print(f"Found <head> tag in {filename}:")
print("Inserting Google Analytics code...")
head_tag.insert(0, BeautifulSoup(ga_code, "html.parser"))

# Write the modified HTML content back to the file
with open(filepath, "w", encoding="utf-8") as file:
file.write(str(soup))

print("Google Analytics code insertion completed.")

0 comments on commit b7c4f76

Please sign in to comment.