Skip to content

Instantly share code, notes, and snippets.

@dccampbell
Created March 6, 2021 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dccampbell/81f6e919287208a215d7bd3833461a5d to your computer and use it in GitHub Desktop.
Save dccampbell/81f6e919287208a215d7bd3833461a5d to your computer and use it in GitHub Desktop.
Webflow 301 Redirects Batch Updater
/**
* Console-friendly function to batch update 301 redirects in Webflow.
* Existing redirects will be replaced when source matches but target doesn't.
* A rule w/ an empty target will remove existing matches but not replace them.
* Small wait time between each add/remove to allow ajax calls time to finish.
* Intended for use here: https://webflow.com/dashboard/sites/YOURSITE/hosting
* @example updateWebflowRedirects( [{ source: "/old", target: "/new" }] );
*/
async function updateWebflowRedirects(rules) {
if(!rules || !rules[0] || typeof rules[0].source !== 'string') {
throw new Error('Argument Error - Expected: [{source:"string",target:"string"},{...},...]');
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const hostingContainer = document.getElementsByClassName('hosting-tab')[0];
const hostingController = angular.element(hostingContainer);
const scope = hostingController.scope();
for(let rule of rules) {
let matchedRule = scope.redirects.find(redirect => redirect.src === rule.source);
if(matchedRule !== undefined) {
if(matchedRule.target === rule.target) {
continue;
}
console.log('Remove Redirect: ' + rule.source);
scope.removeRedirect(rule.source);
await sleep(500);
}
if(typeof rule.target === "string" && rule.target.trim().length) {
console.log('Add Redirect: ' + rule.source + ' => ' + rule.target);
scope.redirectPath = rule.source;
scope.redirectTarget = rule.target;
scope.addRedirect();
await sleep(500);
}
}
}
/*
updateWebflowRedirects([
{source: '/redirect-src-test1', target: '/redirect-tgt-test1'},
{source: '/redirect-src-test2', target: '/redirect-tgt-test2'},
{source: '/redirect-src-test3', target: '/redirect-tgt-test3'},
]);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment