Home > database >  Best (and secure) way to call javascript function (with arguments) using a url from another page
Best (and secure) way to call javascript function (with arguments) using a url from another page

Time:05-02

After reviewing dozens of Stack Overflow posts, I'm thoroughly confused. What I am trying to do is create a URL through an tag on one page that would open another webpage and run a function that requires two arguments. I thought this would be simple but I keep seeing references to "cross site scripting vulnerabilities" and I am not familiar with this potential security problem and feel like I am now playing with fire. I do not want to utilize something — even if the code works — if it opens up security risks. Could someone point me in the right direction with the correct (and most secure) way to do this? I can do my research (and learning) from there. Much appreciated.

CodePudding user response:

For example you can append some parameter at the end of your URL https://your-url/?parameter=hello

When this URL is opened on another webpage you can run JavaScript or a PHP function based on that URL query.

For JavaScript

getUrlParam(slug) {
        let url = new URL(window.location);
        let params = new URLSearchParams(url.search);
        let param = params.get(slug);
        if (param) {
            return param;
        } else {
            return false;
        }
}

console.log(getUrlParam('parameter'));

After that, you can run this function to check if any parameter is passed in that URL or not. If this function returns that's given slug parameter you can run your custom code inside that if condition block

  • Related