Using Query Parameter Bindings

Hello, @chinawoodshed, and welcome to the Builder Forum!

Builder is able to access the URL parameters through its ‘state’ object. Since you are working on a page that is connected to Shopify, you can’t edit the previewing URL in the Visual Editor. While making this, you may need to open the Live Preview option and manually add the parameter to the URL until you publish the page.

Example

Let’s say you have a URL parameter called “paidAd” which has a value of “someProduct”.

www.website.com/page?paidAd=someProduct

Let’s also say that you’d like to bind a text object to display a dynamic message depending on the value of “paidAd”. For example, a message on the announcement bar that advertises “someProduct”.

Bind URL Param data to a text element

Start by dragging a text element onto the page. Then, head into the “DATA” tab and add a new data binding.

Select the “Get Text from…” option, then select the custom code button. In the custom code screen, we can ask for the URL query from the ‘state’ object. Simply typing state.location.query will result in the text box we are using to display “[object, Object]”, which means that we have successfully bound the text to a Javascript object.

Since we know there will be parameter called “paidAd”, we can add that to our binding:

state.location.query.paidAd

This will display the text value that “paidAd” has in the URL.

Finally, let’s add some simple Javascript logic to this, so that we display some more useful text:

if (state.location.query.paidAd === 'someProduct'){
    return 'This is an ad for the product that is available based on the URL.'
} else {
    return 'There is no parameter, so no ad.'
}

Troubleshooting

If you are not able to see things working correctly on the Live Preview version of this page, with the URL parameter added, you can manually ask the browser window for the parameter you’re looking for and assign it to the state object. The following code can be added to the “isBrowser” section of the custom JS + CSS code panel at the bottom of the DATA tab.

(keep in mind that we are looking for a parameter called “paidAd” in this example)

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
//assign a new variable called "paidAdResult" to the result of "paidAd"
const paidAdResult = urlParams.get('paidAd');
//Add a "paidAd" key to the "state" object so that we can use it elsewhere. 
state.paidAd = paidAdResult;

Then, in your text data binding from earlier, you can update the code to now say:

if (state.paidAd === 'someProduct'){
    return 'This is an ad for the product that is available based on the URL.'
} else {
    return 'There is no parameter, so no ad.'
}