Smart 404 Page using Webflow's Native Search Feature

Hey everyone! :wave:

If you’re using Webflow’s native search feature (like me) then I have a handy script to improve the 404 experience on your site. Long story short, I used ChatGPT to write a script that can help users find content even if the page they want is no longer available. Demo

Here’s how it works: when a user visits a page that is no longer available, instead of showing a 404 error, the script automatically redirects the user to a search results page. The search is based on the slug of the 404 page.

To use the script, you’ll need to add it to your website before the closing tag. Here’s the code:

<script>
const currentUrl = window.location.href; // Get the current URL

if (!currentUrl.includes("404")) { // Only replace the URL if the current URL doesn't contain "404"
  const lastSlashIndex = currentUrl.lastIndexOf('/') + 1; // Get the index of the last slash and add 1 to include the character after the slash
  const pathAfterLastSlash = currentUrl.substring(lastSlashIndex); // Get the path after the last slash

  const updatedPath = pathAfterLastSlash.replace(/-/g, '+'); // Replace all occurrences of '-' with '+'
  const updatedUrl = `https://example.com/search?query=${updatedPath}`; // Replace "example.com" with your own domain name, and combine the updated path with the rest of the URL

  window.location.href = updatedUrl; // Replace the current page URL with the updated URL
} else {}
</script>

Here’s what the script does:

  1. It gets the current URL.
  2. It checks if the URL contains “404”. If it does, it doesn’t do anything. If it doesn’t, it continues to the next step.
  3. It gets the path after the last slash in the URL.
  4. It replaces all occurrences of “-” with “+” in the path.
  5. It combines the updated path with your own domain name and a search query parameter.
  6. It prints the updated URL to the console.
  7. It replaces the current page URL with the updated URL.

You’ll need to replace “example.com” with your own domain name in the script.

Once you’ve added the script to your website, your users will automatically be redirected to a search results page if they try to access a page that is no longer available :tada: Pretty cool!

I hope you find this script helpful! Let me know if you have any questions or feedback.

Happy Wednesday :wave:

1 Like