Timothy's Dev Stuff

A collection of code snippets and other developer things.

Redirect with Google Tag Manager

The use case for this is probably very narrow. We had a website we wanted to launch on new hosting. The original website was built with Strikingly. The website was registered with GoDaddy and pointed to Strikingly. The company lost access to the GoDaddy account and could not regain access to point to new hosting. Strikingly also would not add a 301 for us. So, we used Strikingly to add GTM to the site, then fired this script on all pages:

setTimeout(function () {
    window.location.replace("https://website.com/");
}, 15000);

function createAnchorTagAtTopOfBody(message, url) {
    // Create the anchor tag element.
    var anchorTag = document.createElement('a');
    anchorTag.href = url;
    anchorTag.textContent = message;

    // Create a paragraph element to wrap the anchor tag element.
    var paragraphElement = document.createElement('p');
    paragraphElement.appendChild(anchorTag);

    // Create a container for this content
    var elementContainer = document.createElement('div');
    elementContainer.appendChild(paragraphElement);
    elementContainer.classList.add("redirect-notification");

    // Prepend the paragraph element to the body element.
    document.body.prepend(elementContainer);

    // Create styles for this content
    var styleTag = document.createElement('style');
    styleTag.textContent = '.redirect-notification {display: flex;padding: 18px;align-items: center;justify-content: center; font-weight: bold; font-size: 18px;}';
    document.head.appendChild(styleTag);
}

createAnchorTagAtTopOfBody("Click here to check out our new website! Otherwise, we will redirect you shortly.","https://website.com/");

This will prepend a message to the body of the page, at the top, with a link to the new website. The message also lets the user know a redirect will occur “shortly”. Shortly being, in 15 seconds.

This code should be added to a custom code tag in GTM to work. Don’t forget to publish!