i'm using JavaScript to make some small customization in default SharePoint 2013 issue tracker. When user submit an issue (default SharePoint function presave) JavaScript should redirect document to new URL. Everything works fine in Firefox in IE but from unknown reason redirection doesn't work in Chrome.
I'm used location, replace.href, assign etc - result the same - chrome just save the form without redirection. Can you give me any hint why it doesn't work?
I'm using SP 2013 online (and i don't have access to SP designer)
<script src="/sites/SiteAssets/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/sites/SiteAssets/Scripts/sessvars.js"></script>
<script language="javascript" type="text/javascript" src="/sites/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript">
// Here i have small function to get email from sharepoint peoplePicker field
function getEmailFromPeoplePicker(title) {
var ppDiv = $("div[title='" + title + "']")[0];
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var userEmail;
if(userInfo != null)
{
userEmail = userInfo.EntityData.Email;
}
return userEmail;
}
function PreSaveAction(){
// check if there is attachment
if ($('#onetidIOFile').get(0).files.length === 0) {
} else {
OkAttach() //attach file to form
}
//get email from field
var RequestApprover = getEmailFromPeoplePicker('Assigned To');
//create link for redirection with email at the end (ill use it latter for sending emails)
var targetUrl = '/sites/SitePages/RedirectDestination.aspx' + '#' + RequestAprover;
//window.location.href = targetUrl;
//location.replace(targetUrl);
//window.location.assign(targetUrl);
// window.top.location.href = targetUrl;
window.location.assign(targetUrl); // <---------- redirection which works in IE and FireFox but not in Chrome
//window.location.href = targetUrl;
//window.location.assign(targetUrl);
//window.parent.location.href(targetUrl);
//setTimeout(function(){location.href = targetUrl},500);
return true;
}
</script>
I believe you should have "return false;" (instead of return true;) at the end of your PreSaveAction function implementation. Looks like in Chrome redirect takes more time then in other browsers, so Sharepoint continues usual form flow (e.g. continues to PreSaveItem etc.)
Related
I have a section for entering the address in the text field with hints from google, javascript on the home page, which is responsible for transferring address coordinates to a web application on another page, but in my case on the same hosting and domain
the script delays the page load time very much and corrupts the results in google page speed insight
Can someone suggest how to solve it?
here is the script on the home page:
<script>
function go_form() {
var address = document.querySelector('input[name="your-name"]').value;
const lat = search.lat();
const lng = search.lng();
window.location.assign("Https:........... ?code=" + address + "&lat=" + lat + "&lng=" + lng);
}
</script>
<script>
document.querySelector('input[name="your-name"]').addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
console.log(keyCode);
if (keyCode == 13) {
go_form();
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCWlUs26-eUz0JURkuGLHy8_RJl0DBTLOo&libraries=places&callback=initMap"
async defer></script>
<script>
var search = null;
function initMap() {
var input = document.querySelector("input[name='your-name']");
var searchBox = new google.maps.places.SearchBox(input);
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
search = places [0].geometry.location;
});
input.placeholder = "";
}
</script>
You can save the script on a separate file and load it asynchronously:
<script src="path-to-script.js" defer><script>
or
<script src="path-to-script.js" async><script>
(the fastest solution is to use defer in the : https://flaviocopes.com/javascript-async-defer/ )
If the order is important (if you want to load the maps first) only use defer.
This unfortunately does not solve the problem, does anyone else have a solution>
the main page is here:
itrenhold.no
there is a section for entering an address in the text field next to the address "bestill_na"
i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);
I'm trying to save a cookie and then load it again
I have this code
<html>
<head>
<script>
var myCookies = {};
function saveCookies()
{
myCookies["_uuser"] = document.getElementById("user").value;
myCookies["_uuage"] = document.getElementById("age").value;
//Start Reuseable Section
document.cookie = "";
var expiresAttrib = new Date(Date.now()+60*1000).toString();
var cookieString = "";
for (var key in myCookies)
{
cookieString = key+"="+myCookies[key]+";"+expiresAttrib+";";
document.cookie = cookieString;
}
//End Reuseable Section
document.getElementById("out").innerHTML = document.cookie;
}
function loadCookies()
{
//Start Reuseable Section
myCookies = {};
var kv = document.cookie.split(";");
for (var id in kv)
{
var cookie = kv[id].split("=");
myCookies[cookie[0].trim()] = cookie[1];
}
//End Reuseable Section
document.getElementById("user").value = myCookies["_uuser"];
document.getElementById("age").value = myCookies["_uuage"];
}
</script>
</head>
<body>
User: <input type="text" id="user">
Age: <input type="text" id="age">
<button onclick="saveCookies()">Save To Cookies</button>
<button onclick="loadCookies()">Load From Cookies</button>
<p id="out"></p>
</body>
</html>
when I type an input for both name and age, and click on save to cookies,
and then clock on load from cookies, I got this "undefined" for both user and age!!
what's missing in my code, so I can save the cookie
For Chrome cookies can only be set, when the page is running on a webserver.
For example accessed via http://localhost/foo/bar.html or http://127.0.0.1/foo/bar.html
edit: you might check out as well this answer:
where cookie saved for local HTML file
I just tested it myself: it works with Firefox.
Otherwise it would be better for testing such cases, to put up a local webserver like apache
I have tested your code from a web server and it works fine.
You must load it from a web server, rather from the local file system.
JSFiddle is here if you want to prove it for yourself.
https://jsfiddle.net/brx5ropp/
Note that due to JSFiddle limitations I had to move the click triggers for the buttons to code like this:
document.getElementById("load").addEventListener("click", loadCookies);
document.getElementById("save").addEventListener("click", saveCookies);
...but that is irrelevant to my answer!
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 want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages simply edit the following variables:
var defaultsLang are the languages that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();