Created
February 18, 2020 15:23
-
-
Save leowebguy/9a43f12cb30bdae77c877b905f2b5628 to your computer and use it in GitHub Desktop.
pass utm parameters from url to iframe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("&"); | |
} |
<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
Hey leowebguy! This looks like exactly what I need, but I tried putting it between the <script> tags in my body and didn't seem to pass the params. Could you tell me if I'm doing it wrong?