Sorry to be harsh, but the world of “user-contributed code” for Hubspot is really amateurish. (Plenty of bad Marketo JS out there, including my own old stuff, but it’s brilliant by comparison.)
Anyway, a friend asked if I’d ever written Redirector LP code for HubSpot like my code for Marketo. He’d seen a bunch of attempts in the HubSpot community, but none of them worked. (They all either missed hits, created a security vulnerability, or used — ugh — a random delay.)
After a little experimentation, I figured out the equivalent code for HubSpot. Download HubSpot HitEvent v1.3.1 from here and host it on your server:
Create an otherwise blank LP and include the JS library directly after the standard HubSpot code:
<!-- Start of HubSpot Embed Code -->
<script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/5483703.js"></script>
<!-- End of HubSpot Embed Code -->
<!-- TEKNKL HubSpot HitEvent addin -->
<script src="https://your.example.com/teknkl-hubspothitevent-v1.3.1.js"></script>
<!-- TEKNKL HubSpot HitEvent addin --> Then set up your allowed origins (i.e. asset hosting domains, to not be an open proxy) and the redirect code:
redirect: {
const allowedOrigins = [ // which domains are allowed for redirection
"https://pages.example.com",
"https://www.example.com",
"https://example.com"
];
const errNoAsset = "Asset URL not found or bad encoding."; // message when no asset in hash
const errInvalidAsset = "Asset URL not allowed."; // when asset not our domain
const redirectMs = 2000;
let assetURL;
try {
assetURL = new URL(decodeURIComponent(document.location.hash.substring(1)));
} catch(e){
document.body.append(errNoAsset);
break redirect;
}
if( !allowedOrigins.includes(assetURL.origin) ){
document.body.append(errInvalidAsset);
break redirect;
}
enableHubspotHitEvent({ forceAfter: redirectMs, debug: true });
document.addEventListener("hubspot.trackPageView", function (e) {
document.body.append(`Redirecting to <${assetURL.href}>.`);
document.location.href = assetURL.href;
});
}For simplicity, I used the same approach as the Marketo LP. allowedOrigins is an array of origins, errNoAsset and errInvalidAsset are error messages, redirectMs the fallback timeout (timeout is used only if the HubSpot JS is blocked).
At its simplest, build a Redirector LP URL like so:
https://redirectorpage.example.com#https://www.example.com/asset.pdfBut you should percent-encode the asset URL to not lose anything in edge cases:[1]
https://redirectorpage.example.com#https%3A%2F%2Fwww.example.com%2Fasset.pdfNotes
[1] If the asset URL already has reserved characters that needed encoding, you don’t want to lose that. Like if the bare asset URL is:
https://www.example.com/assets/?asset=me%26mrjones.pdfYou need that %26 encoded to %2526 in the Redirector LP URL. Obviously best to avoid such situations, but they’re always lurking.