javascripttampermonkeyuserscripts

UserScript Update Link According to Original Link


What I want is when I visit a specific website that all urls on the PAGE that match (example.com/view=list or example.com/view=card or example.com/view=posts etc..) are changed to:

example.com/view=(card/post/list/poster)

For now I have this:

(function() {
    'use strict';

var anchors = document.querySelectorAll('a[href^="https://example.com/t?view=card"], a[href^="https://example.com/t?view=list"], a[href^="https://example.com/t?view=group"], a[href^="https://example.com/t?view=poster"]');
Array.prototype.forEach.call(anchors, function (element, index) {
    element.href = "https://example.com/t?view=card&categories[0]=1&categories[1]=2&categories[2]=6";
});
})();

So everytime it finds any of the anchors URLS in the page it will change it with that one: example.com/t?view=(card/list/post/poster)&categories[0]=1&categories[1]=2&categories[2]=6

But I would like to automatically change this part "view=card" with the one from original link (card/list/group/poster) in first place.

So it would update to one of these:

example.com/t?view=card&categories[0]=1&categories[1]=2&categories[2]=6
example.com/t?view=list&categories[0]=1&categories[1]=2&categories[2]=6
example.com/t?view=group&categories[0]=1&categories[1]=2&categories[2]=6
example.com/t?view=poster&categories[0]=1&categories[1]=2&categories[2]=6

Solution

  • If you want to extract the view param value from the href, it can be simply done with the URL constructor, which contains a searchParams object that parses the search query into its individual params.

    This snippet will get the view param value, then set the new href using a Template string:

    anchors.forEach( a => {
            const view = new URL(a.href).searchParams.get('view');
            a.href = `https://example.com/t?view=${view}&categories[0]=1&categories[1]=2&categories[2]=6`;
    });