** 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 :)
Related
DISCLAIMER: total beginner with regards to browser extensions and javascript.
BACKGROUND:
I'm trying to develop a proof-of-concept Chrome extension that picks up the text from the input fields in the HTML form of the web page loaded into one tab, and enters the same text on analogous fields of the page in another tab.
In my particular example, the source page is a minimal, local HTML file with two input fields ("user name" and "password"), and the destination is the login page for Apple's Developer Website (https://developer.apple.com/account/).
Reading the official guides and questions here, I've put together some code that seems to work.
THE PROBLEM:
Only text consisting of digits (e.g.: "111111") gets copied from one tab to the other. As soon as my input field contains letters (e.g.: "111111a"), nothing happens.
This is the source page (local file:///):
<html>
<head>
<title>Source Page</title>
<meta charset="utf-8" />
<script src="popup.js"></script>
</head>
<body>
<form>
<input id="accountname_src" name="appleId" placeholder="Apple ID" /><br />
<input id="accountpassword_src" name="password" placeholder="Password" />
</form>
</body>
</html>
The destination HTML (Apple's page) has similar input fields with element ids of accountname and accountpassword, respectively.
My extension's script is as follows:
document.addEventListener('DOMContentLoaded', function(){
// The button in the browser action popup:
var button = document.getElementById('autofill');
var sourceTabID = null;
var destTabID = null;
// Get the SOURCE tab id:
chrome.tabs.query({'title': 'Source Page'}, function(tabArray){
sourceTabID = tabArray[0].id;
});
// Get the DESTINATION tab id:
chrome.tabs.query({'title': 'Sign in with your Apple ID - Apple Developer'}, function(tabArray){
destTabID = tabArray[0].id;
});
if (button !== null){
button.addEventListener('click', function(){
// Get entered text from Source page:
chrome.tabs.executeScript(sourceTabID, {file: "read_input.js"}, function(results){
var credentials = results[0];
var userName = String(credentials[0]);
var password = String(credentials[1]);
// Pass values to Apple login page:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
var autofillCode = insertUserNameCode + insertPasswordCode;
chrome.tabs.executeScript(destTabID, {code:autofillCode});
});
//window.close();
});
}
});
of course, the contents of read_input.js are:
var userName = document.getElementById("accountname_src").value;
var password = document.getElementById("accountpassword_src").value;
var attributes = [userName, password];
attributes // (Final expression, passed to callback of executeScript() as 'results')
It feels like there could be a type inference problem somewhere, but can't tell where.
Bonus Question:
I can read the input fields in the source page using an external script (read_input.js above) and the method chrome.tabs.executeScript(..., file:...; but when I try to write the values to the destination tab using a similar approach, the script does not run (that is why I'm using chrome.tabs.executeScript(..., code:... in my code). Any idea what can be happening?
Silly me (again)... Some console.logging led me in the right direction...
I was not escaping the value in the script; these lines:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
...should be:
var insertUserNameCode = "document.getElementById('accountname').value = '" + userName + "';"
var insertPasswordCode = "document.getElementById('accountpassword').value = '" + password + "';"
(added single ticks around the values)
...so that the code ends up as:
document.getElementById('accountname').value = '111111a';
...instead of:
document.getElementById('accountname').value = 111111a;
Still not sure why a numbers-only value works, though.
I created a button in Salesforce using JavaScript which converts an enquiry (custom object) to a registration (Contact). The button works for myself and any test user I log in as on the same profiles and permissions, however one of my users is report an error when they use the button.
The error is as follows:
'unterminated string constant'
The Code I'm using in the button is as follows:
{!REQUIRESCRIPT('/soap/ajax/27.0/connection.js')}
alert('Migration in progress, this page will refresh once it is complete. Please click ok, Please DO NOT press this button again');
if ('{!Enquiry__c.Surname__c}' != ''){
if ('{!Enquiry__c.Client_if_already_on_the_system__c}' == ''){
var Reg = new sforce.SObject('Contact');
Reg.FirstName = '{!Enquiry__c.First_Name__c}';
Reg.LastName = '{!Enquiry__c.Surname__c}';
Reg.Gender__c = '{!Enquiry__c.Gender__c}';
Reg.MailingStreet = '{!Enquiry__c.Address__c}';
Reg.MailingPostalCode = '{!Enquiry__c.Post_Code__c}';
Reg.MailingCity = '{!Enquiry__c.City_Town__c}';
Reg.MailingState = '{!Enquiry__c.County__c}';
Reg.HomePhone = '{!Enquiry__c.Home_Number__c}';
Reg.MobilePhone = '{!Enquiry__c.Mobile_Number__c}';
Reg.Email = '{!Enquiry__c.E_mail__c}';
Reg.Lastest_Enquiry__c = '{!Enquiry__c.Id}';
result = sforce.connection.create([Reg]);
if (result[0].success == 'true'){
alert('A new Registration with the name - ' + Reg.FirstName + ' ' + Reg.LastName + ' was successfully created, Please DO NOT press this button again as duplication\'s will be created, Your client will be automatically connected to this enquiry');
javascript: document.location.reload(true);
}
}else{
alert('Cannot Migrate to Registration as there is already a Client connected to this Enquiry');
}
}else{
alert('Cannot Migrate to Registration as Surname is blank!');
}
The user has told me they are using IE as a browser, I've tested the button on Chrome, Edge and the most up to date IE. Anyone have any ideas of whats wrong?
what is the type for Reg.FirstName and LastName? Are you using textarea type for these two fields?
Because if user enter any of the name with a carriage return \r or \n alert will fail with the same error and it will be a random based on the input.
I need to add a 'Send Message' button which takes the username of the user that message will be sent to, goes to a link and put this username to the 'To' field of the message form.
This is my code
function sendmessage() {
var x;
//geting the username
x = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = x.substring(x.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
//to get the username parameter from URL on new page
var z=window.location.search.substr(1);
//to get rid of some part of the username parameter
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
//to put the username to 'To' field
document.getElementById("search-q").value= a;
}
Now the problem is that the new page is opened with the parameter. And as a seperate case I can get a parameter from a URL then put it in a field. But I cannot do these two together.
Thanks for the answers!
What you are trying to do is impossible.
As I said in my comment you are navigating away from the page when you set the location. The code after that will not run on the next page. That code needs to live on the next page. That code would have to be executed on page load or document ready.
ok. thanks for the answers. I solve the issue and it works. I am posting the code to help anyone struggling on this problem like me.
The code is divided into two pieces.
<script>
function sendmessage() {
var y;
//geting the username
y = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = y.substring(y.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
}
</script>
<script>
//code running after page-load
window.onload = function() {
var z=window.location.search.substr(1);
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
document.getElementById("search-q").value= a;
}
</script>
this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
So I have a list of users registered on my site in 1 column, in the 2nd is their email address with a checkbox next to it. On this page a user can check the box (or multiples) and click a submit button. Once they do that it will generate a list of the emails semicolon separated.
My issue is after they hit submit the lists generates, but the first email address has "undefined" written right next to it.. so instead of saying "domain1#test.com; domain2#test.com" it reads "undefindeddomain1#test.com; domain2#test.com".
Here is my jQuery:
jQuery(document).ready(function() {
jQuery('#memberSubmit').click(function() {
var emailList;
jQuery('.email-members input:checked').each(function() {
var $this = jQuery(this);
emailList += $this.next('a').html() + "; ";
});
jQuery('.email-message').hide();
jQuery('.email-members').hide();
jQuery('.email-checks').hide();
jQuery('#memberSubmit').hide();
jQuery('.email-results a').attr('href', "mailto: " + emailList).fadeIn(2000);
jQuery('.email-results .email-list p').html(emailList).fadeIn(2000);
jQuery('.email-results h2').fadeIn(2000);
jQuery('.email-results p').fadeIn(2000);
jQuery('.email-list h2').fadeIn(2000);
//console.info('Emails: ' + emailList);
});
});
I think my error is on the line: emailList += $this.next('a').html() + "; ";
But I am not sure... any ideas?
Thanks!
Initialize the emailList the variable first, that means it doesn't start at undefined when you perform your first go around. Coincidently, when you're calling += for the first time, it's actually converting undefined to a string, thus meaning your string always starting with that.
var emailList = "";
Try replacing emailList's declaration with this code:
var emailList = "";
That's because emailList starts out as undefined if you don't initialize it. Therefore undefined + "this is a test" would turn out as undefinedthis is a test.