Am trying to create a link to create an email to send information to the user, the body of which needs to be filled with data generated by a javascript function, and hope that someone can help.
Idealy, if I could substitute the 'body_blurb' below, with a string returned from a javascript function called at the time of clicking that'd be perfect.
e-mail data
Appreciate your time
I just assigned an id to the link here, but you could create something more generic if you wanted. Once you have an onclick handler created you can access the url with href. Set this to whatever you want.
http://jsfiddle.net/f3ZZL/1
var link = document.getElementById('email');
link.onclick = function() {
this.href = "mailto:you#yourdomain.com?subject=Data&body=";
this.href += getBody();
};
function getBody() {
return 'HelloWorld';
}
Here is the no-spam method
var link = document.getElementById('email');
link.onclick = function() {
var name = "you";
var domain = "yourdomain.com";
var linker = "mailto:" + name + '#' + domain + "?subject=Data&body=";
linker += getBody();
link.setAttribute("href", linker);
};
function getBody() {
return 'HelloWorld';
}
On Fiddle
You don't actually need to set the href value. What you're really trying to do is send the browser to a mailto: URL: the href is just a means to that end.
Leave the href blank and make the link have an onClick handler. In the onClick, feed the browser the mailto: URL (after you build it using your variable). Presto, done.
Related
In my website I have some part when you 'click' on it, It will show a (pop-up) div & grays the rest of the website, However I want to make a link/hashlink for that state.. something like this ( http://www.mywebsite.com/show-pop-up ), So whenever my visitors type the link above in their browser and go, They will come to my website with (the pop-up visible).
I saw this in Trello.com & Behance.com (When you click in a project it will show as pop-up with a new link in the browser).
Note: I need this in 'pure' JavaScript.
There are several ways you can achieve this. One of the following options may work for you.
Option 1: using hashes. Consider the following url: www.mywebsite.com/index.html#popup. You can retrieve the #popup value on startup of your website and act accordingly. See the code sample below.
document.addEventListener("DOMContentLoaded", function(event) {
// Website has loaded.
var hash = location.hash
// Check if the hash exists and is popup.
if (hash && hash === 'popup') {
// Show your popup
}
});
Another option would be to use query strings. Consider the following url: www.mywebsite.com?popup=true. First you have to retrieve the query strings, using for example the following function. Afterwards check if the popup querystring has been used.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var popup = getParameterByName('popup');
// Check if we have the popup parameter.
if (popup) {
// Show popup
}
Suggest using
http://www.mywebsite.com#show-pop-up
instead of
http://www.mywebsite.com/show-pop-up
then using
if(location.hash === '#show-pop-up') {
// show your popup
}
on page loaded.
I am not sure if what I'm trying to do is possible or if I'm going about this the right way. In some circumstances I want them to have a GET parameter as part of the URL. I want the receiving page to be able to differentiate whether the sending load has a parameter or not and adjust accordingly.
Here is what I have that is sending the load:
$(document).ready(function () {
$("a").click(function () {
$("div.pageContent").html('');
$("div.pageContent").load($(this).attr('href'));
return false;
});
});
In this case, the load could have "example.php" or "example.php?key=value". In looking around (primarily on this site), I've found things that seem to be close, but don't quite get there. In the page that is getting loaded (example.php), I have the following:
function $_GET(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
$(document).ready(function () {
var URL = "example2.php";
if ($_GET('key'))
{
URL = "example2.php?key=" + $_GET('key');
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
If the sending source includes a query string, I want to add that to the URL and load it in a div that is unique to this page, otherwise I want to just load it as is without the query string. The big issue I'm running into (I believe) is since this is coming from an AJAX call, the "window.location.href" is not what was sent from the JQuery but rather the URL of the root page which never changes. Is there a way to be able to know what the full URL is that was sent from the load() in the first page by the second one?
Thank you in advance for your help.
I realized that the GET parameters were getting passed as I could access them through php without issue. I didn't know that I could insert php code into a javascript block but once I tried it, all worked out. My new code looks like this:
$(document).ready(function () {
var URL = "example2.php";
var myValue = "<?php echo $_GET['key']; ?>";
if (myValue !== "")
{
URL = "example2.php?key=" + myValue;
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
I was able to get rid of the GET function out of javascript entirely. I probably made this much more difficult from the start but hopefully it can help someone else in the future.
My company is serving up PPC landing pages with Unbounce (on a subdomain), which then links back to our website. We're using the following code to append the AdWords gclid variable to outgoing links:
$(document).ready(function() {var params = window.location.search.replace(/\+/g,'%20'); var button = $('a').each( function(i) {this.href = this.href + params;});});
The issue arises when the Gclid gets appended to a URL that already has a parameter (like our checkout forms). You end up with a URL that looks like this:
domain.com/checkout?EventID=15546?Gclid=jdkI324kd
I'm wondering if there's a way to change the Glid's '?' to an '&' for certain URLs that already have parameters, while keeping the existing functionality of using the '?' for the others.
Thanks!
Edit: Seems like there's some redirection going on, this is how the href looks for the links in question:
http://domain.com/lp/clkg/https/domain.com/cart.aspx?EventID=125160?gclid=CPfO1JaOx7oCFQZyQgod5A4AFw
Simply replace it yourself:
$(document).ready(function() {
var params = window.location.search.replace(/\+/g,'%20');
var button = $('a').each( function(i) {
if (this.href.indexOf('?') == -1) {
this.href = this.href + params;
} else if (params.length) {
this.href = this.href + '&' + params.substr(1);
}
});
});
Edit: and are you aware that you are replacing subsequent spaces with only one single '%20'?
I have the following code as a Google Apps Script (deployed as a web app) and have inserted it into my Google Enterprise page as a Google Apps Script Gadget. The UI (panel) loads properly with the label, textBox and button, but when I enter in text and click the button, I get the following error:
Error encountered: The resource you requested could not be located.
Here is my script:
function doGet(e) {
// create all UI elements
var myApp = UiApp.createApplication();
var panel = myApp.createVerticalPanel();
var label = myApp.createLabel('Please enter the name of your new site:');
var textBox = myApp.createTextBox().setName('txtSiteName');
var button = myApp.createButton('Create Site');
var btnHandler = myApp.createServerHandler('createNewSite');
button.addClickHandler(btnHandler);
btnHandler.addCallbackElement(panel);
// add all UI elements to the panel
panel.add(label);
panel.add(textBox);
panel.add(button);
// add the panel to the app
myApp.add(panel);
// return the app to the browser to be displayed
return myApp;
}
// button server handler
function createNewSite(e) {
var domain = SitesApp.getActiveSite().getUrl();
var siteName = e.parameter.txtSiteName;
var newSite = SitesApp.createSite(domain, siteName, 'script_center_demo', "this is just a test page");
return app.close();
}
Also, what is the difference between createSite() and createWebPage()?
EDIT: Ok, so using the same doGet() function above, my createNewSite() function could look like this?
function createNewSite(e) {
var domain = 'my-domain.com';
var siteName = e.parameter.txtSiteName;
var newPage = SitesApp.createSite(domain, siteName, 'script_center_demo', "this is just a test page");
var pageName = 'script_center_demo';
var html = '<div><p>This project aims to....</p></div>';
var site = SitesApp.getSite(domain, site);
site.createWebPage('Script Center Demo', pageName, html);
return app.close();
}
Look at this line:
var domain = SitesApp.getActiveSite().getUrl();
You're need to obtain a domain, e.g. example.com, but this line will yield a URI containing google's domain, and a resource path (that contains your domain). Example:
https://sites.google.com/a/example.com/mySite/
^^^^^^^^^^^
When you attempt to create a new site, it cannot be found as a domain. You need to strip the result of getUrl() down to just the domain name.
If you're the Domain administrator, you can use this instead:
var domain = UserManager.getDomain();
Ordinary domain users don't have access to the UserManager Service, so they would need to parse the site URL to extract their domain. I suggest using parseUri by Steven Levithan to handle the task:
var uri = parseUri(SitesApp.getActiveSite().getUrl());
var domain = parseUri(uri.path.slice(3)).host;
The .slice(3) operation is intended to remove /a/ from the path property of the parsed Site URI. This works on my accounts in multiple domains today - ymmv.
After that, we treat the remaining path as a URI and invoke parseUri() again, extracting the host property, which should be our domain.
Also, what is the difference between createSite() and createWebPage()?
You create an instance of a Site, using the Sites service method SiteApp.createSite. Not much to look at, a Site object is a container, a skeleton - you use the Site.createWebPage() method to create Web Pages that will be contained in the Site, and visible to users, mainly via web browsers.
Edit - Debugging Results
Debugging WebApps is tricky. Get familiar with "View - Execution Transcript", since it will show a trace of execution for your createNewSite() handler function when it's invoked. Using that technique, here's what I found, part 1:
We can't call SitesApp.getActiveSite().getUrl() in the handler, because when it's invoked there is no active site. You're already using the simple work-around of hard-coding the domain.
When trying to get a handle on the new site, you have var site = SitesApp.getSite(domain, site);. This is where your latest "resource error" message was coming from. The site parameter is left-over from insertion of the function - it needs to be a string, matching the site name used in createSite().
You're returning app.close(), but have no app defined in the function.
With those problems fixed, here's problems, part 2:
The dialog lets users enter a site name, but there are restrictions on those that need to be followed to make createSite succeed. The simplest rule is that the site name must be lower case. Why not let users enter the site title, and derive the name from that?
What if the site already exists? That's not handled. Same thing for the page creation, later on.
There's no feedback to the user. The example below has very rudimentary status updates in it, which are appended to the UI.
updated code
function createNewSite(e) {
var app = UiApp.getActiveApplication();
var domain = 'mitel.com';
var siteTitle = e.parameter.txtSiteName;
var siteName = siteTitle.toLowerCase();
var result = 'Results: ';
var site = SitesApp.getSite(domain, siteName); // Check if site already exists
if (site)
result += 'Site "' + siteName + '" exists, ';
else {
// Doesn't exist, so create it
site = SitesApp.createSite(domain, siteName, siteTitle, "this is just a test page");
result += 'Site "' + siteName + '" created with title "' + siteTitle + '", ';
}
var pageName = 'script_center_demo';
var html = '<div><p>This project aims to....</p></div>';
var page = site.getChildByName(pageName); // Check if page already exists
if (page)
result += 'Page "' + pageName + '" exists, ';
else {
// Doesn't exist, so create it
page = site.createWebPage('Script Center Demo', pageName, html);
result += 'Page "' + pageName + '" created, ';
}
result += 'Done.';
// Add result text to UI
var uiResult = app.createLabel(result, true);
app.add(uiResult);
return app.close();
}
<script type="text/javascript">
var email = document.write(localStorage.getItem('email'));
var pass = document.write(localStorage.getItem('pass'));
var url = document.write(document.URL);
document.location.href = url+"?email="+email+"&pass="+pass;
</script>
But when I enter the page I left the url like this:
http://example.com/undefined?email=undefined&pass=undefined
Not happening ... Anyone know the problem? Thank you very much!
Well, what's up with document.write(…) in here? You don't want to print out anything:
var email = localStorage.getItem('email');
But if you want to print out the values for testing:
var email = localStorage.getItem('email');
document.write(email);
(See also console.log(…))
You should escape the parameters using encodeURIComponent(…):
location.href = url + "?email=" + encodeURIComponent(email) +
"&pass=" + encodeURIComponent(pass);
Also you should not use document.write anyhow. There are plenty more reasonable methods to change the content dynamically on you website.
You should not send a password using GET requests, as they will appear the browser, proxy and server logs. Use POST requests through invisible forms.