Just sharing this little script we created to easily pull any number of custom parameters from the page URL and replace them with placeholder you set in webflow text or custom HTML embed.
The Webflow project is here
The live demo is here (try changing the URL parameters): https://webflow-demos.webflow.io/insert-custom-url-parameters?custom_text_title=Title%20from%20URL!&custom_text_subtitle=Try%20changing%20this%20subtitle%20in%20the%20URL&custom_thref_link=https://google.com&custom_src_image=https://gizzmo.si/uploads/emoji/5.png
Implementation:
- Copy this script to your page (or project) custom code, before the tag (2nd custom code field):
<script>
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = decodeURIComponent(value);
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], decodeURIComponent(value)];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(decodeURIComponent(value));
}
}
return query_string;
}
var query_string = window.location.search.replace('?','');
var parsed_qs = parse_query_string(query_string);
for(key in parsed_qs) {
if( $( "a[href='[["+key+"]]']" ).length > 0 ) {
$( "a[href='[["+key+"]]']" ).attr('href', parsed_qs[key]);
}
if( $( "img[src='[["+key+"]]']" ).length > 0 ) {
$( "img[src='[["+key+"]]']" ).attr('src', parsed_qs[key]);
}
}
$('body *').each(function(index, element) {
var unstripped = $.trim($(element).text());
var stripped = unstripped.replace('[[','').replace(']]','');
if(typeof parsed_qs[stripped] !== "undefined") {
$(element).html($(element).html().replace(unstripped, parsed_qs[stripped]));
}
});
</script>
- Insert placeholders to your webflow page:
- For text (use anywhere in the project)t: [[custom_text_anything]]
- For image/video source (HTML embed): [[custom_src_anything]]
- For link href (HTML embed): [[custom_href_anything]]
- Just insert the parameters to your URL, named the same as placeholders (without [[ and ]]), like on the demo url above.
Important notes:
The script replaces stuff in the DOM after its load, this usually happens quite fast, however in cases of big pages/slow connection/many parameters, there may be a “flash/replacement” visible on load. In this case it would be better to modify the script so it would pull get parameters right on the load and insert them to specified places.
If the URL parameter is empty or missing, nothing is displayed.
Tip: You can use onerror="this.src='backup-image.jpg';"
added before src
of the image/video to prevent broken images in case URL parameter is not a valid source. Shown in the demo.