Fix Avito sort

Prevents Avito from resetting sort option at Seatch. Helps to presume sort of products by price decending, when Avito.ru silently removes it from the request 10 seconsa after page load.

// ==UserScript==
// @name            Fix Avito sort
// @namespace       https://github.com/MihaxXx
// @version         0.1.2
// @description     Prevents Avito from resetting sort option at Seatch. Helps to presume sort of products by price decending, when Avito.ru silently removes it from the request 10 seconsa after page load.
// @description:ru  Предотвращает сброс выбранной сортировки в поиске на Авито. Помогает сохранить сортировку "Дешевле" при смене страницы, т.к. Авито её тихо удаляет из запроса через 10 секунд после перехода.
// @author          Miha_xXx
// @license         MIT
// @match           https://www.avito.ru/*
// @icon            https://www.google.com/s2/favicons?sz=64&domain=avito.ru
// @grant           window.onurlchange
// @grant           GM_getValue
// @grant           GM_setValue
// ==/UserScript==


/// Fallback for browsers without Naveration API support https://caniuse.com/mdn-api_navigation
function preventRemovingSortLegacy(e){
    var oldUrlRaw = GM_getValue("avito_previous","");
    GM_setValue("avito_previous",e.url);

    if(!oldUrlRaw){
        return;
    }
    var oldUrl = new URL(oldUrlRaw);
    var newUrl = new URL(e.url);

    var fakeEvent = {
        currentTarget: {currentEntry: {url: oldUrl.href}},
        destination: {url: newUrl.href}
    }
    preventRemovingSort(fakeEvent);
}

function preventRemovingSort(e){
    console.log('location changed!', e);
    const oldUrl = new URL(e.currentTarget.currentEntry.url);
    const newUrl = new URL(e.destination.url);
    if(newUrl.pathname && oldUrl.pathname === newUrl.pathname && oldUrl.searchParams.get("s") && !newUrl.searchParams.get("s")){
        newUrl.searchParams.append("s", oldUrl.searchParams.get("s"));
        window.history.replaceState({}, null, newUrl.href);
    }

}

(function() {
    'use strict';
    if(window.navigation) {
        window.navigation.addEventListener('navigate', preventRemovingSort)
    } else if (window.onurlchange === null) {
        window.addEventListener('urlchange', preventRemovingSortLegacy);
    }
})();