TransWikia.com

Replace Source query string value without redirecting

SharePoint Asked by LeonidasFett on November 28, 2021

is there some way to replace the Source query string parameter in SharePoint without redirecting the user? All the examples I find use location.href=”new url”; which causes the page to immediately reload. However, I just want to actually replace the Source parameter so Sharepoint will redirect to it after the user is done with whatever he is doing.

I already managed to replace the query string with the following code:

$(document).ready(() => {
    var redirectUrl = _spPageContextInfo.webAbsoluteUrl + "/" + _spPageContextInfo.layoutsUrl + "/Redirect.aspx";
    var queryParameters = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    queryParameters['Source'] = redirectUrl;

    console.log(location.search.replace(location.search, 
$.param(queryParameters)));
});

Now I just need to replace the Source query parameter with the new value. How do I do this?

One Answer

If you are working with browsers that support the HTML5 History API, you could use replaceState:

$(document).ready(() => {
    var redirectUrl = _spPageContextInfo.webAbsoluteUrl + "/" + _spPageContextInfo.layoutsUrl + "/Redirect.aspx";

    var queryParameters = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;

    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    queryParameters['Source'] = redirectUrl;

    var updatedParams = location.search.replace(location.search, $.param(queryParameters));

    if (history.replaceState) {
        var newurl = window.location.origin + window.location.pathname + "?" + updatedParams;
        window.history.replaceState({ path: newurl }, '', newurl);
    }
});

However, if you are trying to modify the source on a form in SharePoint, that won't be sufficient. Some onclick events are populated when the page loads with the initial Source value and these events will have to be override as well since they will redirect to the previous value:

$("#part1").on("click", "input[value='Cancel']", function (e) {
    e.preventDefault();
    window.location.href = redirectUrl;
});

$("#Ribbon.ListForm.Edit.Commit.Cancel-Large").click(function (e) {
    e.preventDefault();
    window.location.href = redirectUrl;
});

Answered by horinedev on November 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP