Skip to content

Instantly share code, notes, and snippets.

@leowebguy
Created February 18, 2020 15:23
Show Gist options
  • Save leowebguy/9a43f12cb30bdae77c877b905f2b5628 to your computer and use it in GitHub Desktop.
Save leowebguy/9a43f12cb30bdae77c877b905f2b5628 to your computer and use it in GitHub Desktop.
pass utm parameters from url to iframe
if (window.location.search) {
const urlParams = new URLSearchParams(window.location.search);
var utms = [
"utm_medium=" + urlParams.get('utm_medium'),
"utm_source=" + urlParams.get('utm_source'),
"utm_campaign=" + urlParams.get('utm_campaign'),
"utm_content=" + urlParams.get('utm_content')
];
document.querySelectorAll('iframe')[0].src = document.querySelectorAll('iframe')[0].src + "&" + utms.join("&");
}
@leowebguy
Copy link
Author

<html>
<body>
<iframe src="https://somepage.com"></iframe>
<script>
if (window.location.search) {
	const urlParams = new URLSearchParams(window.location.search);
	var utms = [
		"utm_medium=" + urlParams.get('utm_medium'),
		"utm_source=" + urlParams.get('utm_source'),
		"utm_campaign=" + urlParams.get('utm_campaign'),
		"utm_content=" + urlParams.get('utm_content')
	];
	document.querySelectorAll('iframe')[0].src = document.querySelectorAll('iframe')[0].src + "&" + utms.join("&");
}
</script>
</body>
</html>

this should grab parameters from https://mywebsite.com?utm_medium=123&utm_source=abc&utm_campaign=xyz&utm_content=cdf and append it to your iframe like <iframe src="https://somepage.com?utm_medium=123&utm_source=abc&utm_campaign=xyz&utm_content=cdf"></iframe>

maybe you should try deferring this script like

<script>
window.addEventListener('DOMContentLoaded', function() { // make sure page is all loaded
   if (window.location.search) { ... }
});
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment