When using content staging in HubSpot you can easily test and preview design changes but the menu does not update to use the new staging domain. So you have to preview each page individually. This can be an issue when you are working on a HubSpot website rebrand and the client needs to click through the site.
The code below checks if you are visiting a sandbox environment. If you are, it then changes the menu links to match the sandbox domain. Be sure to update the domain in the code with your domain.
Plain Javascript Version
function isSandbox() {
// Check if the current page URL contains "sandbox.hs-sites"
var url = window.location.href;
var index = url.indexOf("sandbox.hs-sites");
return index > -1;
}
if (isSandbox()) {
// Disable click events since we are changing the links
var menuLinks = document.querySelectorAll('.header__container a');
for (var i = 0; i < menuLinks.length; i++) {
menuLinks[i].style.pointerEvents = 'none';
}
// Wait for the menu to load and hubspot to add click tracking to links
window.addEventListener('load', function() {
// Select all menu anchor links
var menuLinks = document.querySelectorAll('.header__container a');
for (var i = 0; i < menuLinks.length; i++) {
menuLinks[i].style.pointerEvents = 'auto';
var domain = document.domain;
var oldUrl = menuLinks[i].getAttribute('href'); // Get current url
// Change your domain
var newUrl = oldUrl.replace("https://yourprimarydomain.com", "https://"+domain); // Create new url
menuLinks[i].setAttribute('href', newUrl); // Set herf value
}
// add a badge to make it clear you're visiting a staging environment
var badge = document.createElement('div');
badge.innerHTML = 'STAGING';
badge.style.backgroundColor = 'rgba(0,0,0,0.5)';
badge.style.padding = '10px';
badge.style.color = '#fff';
badge.style.position = 'fixed';
badge.style.top = 0;
badge.style.left = 0;
badge.style.fontSize = '10px';
document.body.appendChild(badge);
});
}
Jquery Version
// Is this a hubspot sandbox? if (window.location.href.indexOf("sandbox.hs-sites") > -1) { // Disable click events since we are changing the links $('#hs_menu_wrapper_menu a').css('pointer-events', 'none'); // Wait for the menu to load and hubspot to add click tracking to links $(window).load(function() { // Select all menu anchor links $('#hs_menu_wrapper_menu a').each(function(){ $(this).css('pointer-events', 'auto'); var domain = document.domain; var oldUrl = $(this).attr("href"); // Get current url // Change your domain var newUrl = oldUrl.replace("https://www.YOURDOMAIN.com", "http://"+domain); // Create new url $(this).attr("href", newUrl); // Set herf value }); // add a badge to make it clear you're visiting a staging environment $(document.body).append('<div style="background-color:rgba(0,0,0,0.5);padding:10px;color:#fff;position:fixed;top:0;left:0;font-size:10px;">STAGING</div>'); }); }