简体   繁体   中英

Mailto: subject as a variable

** EDIT: Thanks, Shivan Raptor! I kinda forgot about "encodeURIcomponent()"! **

For some reason, I'm making a Javascript bookmarklet that quickly emails one of my two emails. (I'll just show the indented JS to make it easier, as I can convert it.) It uses a couple variables for the subject and body, which are inputted by prompts.

var address = confirm("School email?");

        var sub = prompt("What is the subject?");

        var bod = prompt("What would you like the message to read?");

        if(address == true) {
            window.location.assign("mailto:areiter@hightechhigh.org?Subject=sub&body=bod");
            alert("Message sent to 'areiter@hightechhigh.org'.");
        }
        else {
            window.location.assign("mailto:burningphantom13@gmail.com?Subject=sub&body=bod");
            alert("Message sent to 'areiter@hightechhigh.org'.");
        }

The only problem is that the variables "sub" and "bod" are what the subject and body appear as, respectively. So the code opens up Outlook, and has an email ready to be sent with the subject "sub" and "bod" in the body. Is there a way for the subject and body of a Javascript code to be the values of variables? Remember, it's going to be a bookmark, so there can't be any HTML.

You can replace :

window.location.assign("mailto:areiter@hightechhigh.org?Subject=sub&body=bod");

with:

window.location.assign("mailto:areiter@hightechhigh.org?Subject=" + encodeURIComponent(sub) + "&body=" + encodeURIComponent(bod));

so that the variable sub and bod will be dynamic according to user input. encodeURIComponent encodes the parameters, so if the user inputs special characters, the codes will not crash.

Change code as following,

    var address = confirm("School email?");

    var sub = prompt("What is the subject?");

    var bod = prompt("What would you like the message to read?");

    if(address == true) {
        window.location.assign("mailto:areiter@hightechhigh.org?Subject=" + sub + "&body=" + bod);
        alert("Message sent to 'areiter@hightechhigh.org'.");
    }
    else {
        window.location.assign("mailto:burningphantom13@gmail.com?Subject=" + sub + "&body=" + bod);
        alert("Message sent to 'areiter@hightechhigh.org'.");
    }

Hope this will work :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM