injecting data from URL to inputbox - javascript

I want to add some data from url to an input-box with an unique name ( not id ) , Because I don't have any accesses on the page I can't edit it with ids or sth.
<input type="text" name="test">
and sth like that :
site.com/index.php?test=text123

Ok from what I understand, You want to put get data from URL into your input fields.
First, when you open the tab, put the 'document' of the tab into a global variable
var url = "www.url.com"; //the url of the page to open in tab
var tabInstance= window.open(url);
tabDocument = tabInstance.document; //tabDocument is a global variable
Now, assuming the data you want to put into the tab is in the URL of the page that is opening the tab
function populateInputFields(){
var data = parseURLParams(document.URL); //get url data in json format.
if(!data) return; //if no get parameters found
//iterate json
for(var key in data){//for each key in the json data
var value = data[key]; //get the 'value' for corresponding key
var element = tabDocument.getElementsByTagName(key)[0];//get the input element
if(element && element.tagName == 'input'){//check if element exists and is of type input
element.value = value;
}
}
}
Implementation of parseURLParams take from here: How to read GET data from a URL using JavaScript?
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") {
return;
}
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=");
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) {
parms[n] = [];
}
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}

Related

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

Remove Portion of Query String using JS based on their value without page reload

How can I remove just certain parameters from an URL based on their parameters?
For example, If I want to programmatically remove any parameter sets that contain the value "all" i.e. when an Ajax event completes.
www.foobar.com/page?year=all&language=all&gender=female
to:
www.foobar.com/page?gender=female
Using JS or jQuery.
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// Add new parameters or update existing ones
queryParameters['newParameter'] = 'new parameter';
queryParameters['existingParameter'] = 'new value';
location.search = $.param(queryParameters);
// Handy function to parse the URL and get a map of the query parameters
function parseQueryParameters(url) {
var qp = {};
if (!url) {
return qp;
}
var queryString = url.split('?')[1];
if (!queryString) {
return qp;
}
return queryString.split('&')
.reduce(function(m, d) {
var splits = d.split('=');
var key = splits[0];
var value = splits[1];
if (key && value) {
m[key] = value;
}
return m;
}, qp);
}
//Function to build a url given a map of query parameters
function buildUrl(url, queryParams) {
if (!url) {
return null;
}
if (!queryParams) {
return url;
}
return Object.keys(queryParams)
.reduce(function(m, key, i) {
m += ((i === 0 ? "?" : "&") + key + "=" + queryParams[key]);
return m;
}, url)
}
function cleanUrl(url) {
//If no URL was provided, do nothing
if (!url) return;
//Parse and get all query parameters as a map
var qp = parseQueryParameters(url);
//Create a new map to hold the filtered query parameters
var newQp = {};
//For each query paremeter check the value and add only the required ones to the new map
//PS: You can also use map/reduce/filter to do this
//Using a simple for loop here for clarity
var keys = Object.keys(qp);
for (var i = 0; i < keys.length; i++) {
var currentKey = keys[i];
//Add only if parameter value is not 'all'
if (qp[currentKey] !== 'all') {
newQp[currentKey] = qp[currentKey];
}
}
//Build new URL from filtered query parameters
return buildUrl(url.split('?')[0], newQp);
}
//Call cleanUrl with URL
cleanUrl("http://example.com?a=all&b=all&c=none"); //Returns "http://example.com?c=none"
You can use URL() constructor, URLSearchParams() to get query string of URL as an Array of arrays of properties and values corresponding to query string parameters, Array.prototype.filter() and RegExp.prototype.test() to remove query string parameters from array, and URLSearchParams() again to reconstruct filtered query string parameters
let src = "https://www.foobar.com/page?year=all&language=all&gender=female";
let url = new URL(src);
let re = /all/;
let props = [...new URLSearchParams(url.search)]
.filter(([key, prop]) => !re.test(prop));
url = url.origin + url.pathname;
let params = new URLSearchParams();
props.forEach(([key, prop]) => params.set(key, prop));
url += "?" + params.toString();
console.log(url);

Javascript check if url param exists

I'm running an A/B test to see if showing more items is better for conversion. But it seems that the code sometimes causes errors.. But I can't find any errors and don't know when they occur.
In my test I check whether the url param IC exists and if it doesn't exists I will add this.
This is my code:
function checkIfAlreadyPaginated()
{
var field = 'IC';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
return true;
else if(url.indexOf('&' + field + '=') != -1)
return true;
return false;
}
function insertParam(key, value) {
key = encodeURIComponent (key); value = encodeURIComponent (value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
return '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
return '?'+kvp.join('&');
}
}
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
{
document.location.search = insertParam('IC', itemsPerPage);
}
Does someone spot possible issues? I'm running the test via VWO.com.
If there is a Javascript error you should see it in the browser console and share it with us.
In any case, I would do it by creating a JS Object first. I find it easier to work with.
In the following code I added the option to do the checking for multiple params of the querystring. If you only need to check the IC you can simplify it a bit. I tested it on a blank test.html.
<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');
// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
param = querystringItems[i].split('=');
querystringObject[param[0]] = param[1];
}
// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};
// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
if (typeof querystringObject[key] == 'undefined') {
doreload = true;
// Create the missing parameter and assign the default value
querystringObject[key] = requiredKeys[key];
}
}
// If any of the requiredKeys was missing ...
if (doreload) {
// rebuild the querystring
var querystring = '?';
for (var key in querystringObject) {
querystring+=key+'='+querystringObject[key]+'&';
}
querystring=querystring.substr(0,querystring.length-1);
// reload page
document.location.search = querystring;
}
// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>
Here is an example to check this:
//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
//push its name and value to the final array
params.push(paramArray[i].split('='));
//if the parameter name is IC, output its location in array
if(params[i][0] === 'IC'){
icLoc = i;
}
}
If IC is not found, icLoc will be -1.
If it is found, the value of IC in the URL parameters is params[icLoc][1]
Example result for query string ?foo=bar&code=cool&IC=HelloWorld:
params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'}
icLoc = 2
Example for query string ?foo=bar&code=cool:
params = {'foo': 'bar', 'code': 'cool'}
icLoc = -1
Here id is the param I'm using for a test. Pass the argument which you want to check whether it exists or not.
function queryParamExistUrl(param = '') {
if (new URLSearchParams(window.location.search).get(param) != null)
return true
return false
}
console.log(queryParamExistUrl('id'))

How can I change FlashVars parameters into a URL query string?

I understand that when retrieving an SWF file and passing parameters to that file while doing so, there are two options to do this: using the FlashVars or the query string technique.
Say I wish to obtain the swf file directly via HTTP so that I can download the file, and I know from the source code that the file, when embedded, is passed the the following parameters via FlashVars with the following Javascript code:
// used to validate hour parameter
var numberOfSegments = 1;
var flashvars1 = {};
flashvars1.url = "http://cm.dce.harvard.edu/2014/02/23515/L12/23515-20140502-L12-H264HighBandwidthTalkingHead-16x9.xml";
flashvars1.videoWidth = "374";
flashvars1.videoHeight = "210";
flashvars1.resizable = true;
flashvars1.hour = 1;
flashvars1.autoPlay = true;
flashvars1.largeTH = false;
flashvars1.cdn = false;
//<!--
// This will create or overwrite optional HOUR parameter
// Tests if URL had query argument: "?part=3"
// Checking for part in range prevents flash #1006 error
if (location.search != ""){
var queryStr = location.search.split('?');
if(queryStr.length > 1){
queryStr = queryStr[1];
var queryArray = queryStr.split("&");
for ( var i = 0; i < queryArray.length; i++){
var pair = queryArray[i].split("=");
if ((pair[0] == "part") && (pair.length > 1) && !isNaN(pair[1])){
if((numberOfSegments != null) && (0 < pair[1]) && (pair[1] <= numberOfSegments) ){
flashvars1.hour = pair[1];
} // make sure hour value is in range
} // end if HOUR is part of query
} // end query pair array loop
} // end if query has content
} // end if query exists
// -->
var params1 = {};
params1.quality = "high";
params1.bgcolor = "#ffffff";
params1.allowscriptaccess = "sameDomain";
params1.allowfullscreen = "true";
params1.wmode = "transparent";
var attributes1 = {};
attributes1.id = "flashContent1";
attributes1.name = "flashContent1";
attributes1.align = "middle";
swfobject.embedSWF(
"/flash/FlashViewer.swf", "flashContent1",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars1, params1, attributes1);
How then do I translate FlashVars into a query string I can append at the end of the swf URL?
This should give you the a query string with all the values from the flashvars1 JSON object:
var querystring = "?";
for (var key in flashvars1) {
if (flashvars1.hasOwnProperty(key)) {
querystring += key + "=" + flashvars[key] + "&";
}
}

Full url sharepoint item in Javascript

I'm trying to get the ContentTypeId of an item in sharepoint to get the full url of the item to get the binary of it and after send it to another plateform.
So here i put this code in element.xml to get the list ID and the document ids of the items i'm selecting, after this i send them to an ASPX page in a Sharepoint Dialog to define the destination of the items and after this in the postback, stream the binary and send it to the another platform. The problem is : To get the full url of my items i need ListId, ItemId and ContentTypeId.
Because i've found a code to stream the binary here :
How to Programatically Download files from sharepoint document library
And i need the full url of my items.
Any idea?
thanks
var iddocs ='';
var listId ='';
function geturl()
{
var context = SP.ClientContext.get_current();
this.web = context.get_web();
listId = SP.ListOperation.Selection.getSelectedList();
var list = this.web.get_lists().getById(listId);
var ok = false;
try
{
if ( SP.ListOperation.Selection.getSelectedItems(context) !== false)
{
var items = SP.ListOperation.Selection.getSelectedItems(context);
var url='listId:'+listId+ ' Number of selected items: ' + items.length ;
var i = 0;
if(items.length==0)
{
}else{
while( i != items.length )
{
url += ' Doc' + i + ': ' + items[i].id;
if(i>0){iddocs += '-'};
iddocs += items[i].id;
i++;
};
ok = true;
alert(url+' Id of clicked item:'+{ItemId});
};
};
}
catch(err)
{
};
return ok;
};
function OpenDialog(pidliste) {
var options = SP.UI.$create_DialogOptions();
options.width = 600;
options.height = 600;
options.title = 'Envoyer vers Nuxeo';
options.url ='/_Layouts/SPTest.CustomMenuItem/index.aspx?click={ItemId}';
if(pidliste){options.url += '&ids='+pidliste +'-'+ iddocs;};
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
function CloseCallback(result, target) {
if (result == SP.UI.DialogResult.OK) {
}
if (result == SP.UI.DialogResult.cancel) {
SP.UI.Notify.addNotification('Opération canceled', false, '', null);
}
}
if(geturl())
{
OpenDialog(listId);
}else{
alert('Please select an item');
};
I've found the solution. In fact, items can be reached via :
{SiteUrl}+{ItemUrl}
The download function is linked in my first Post. But it doesn't work for multiple items, with this method you can only reach the properties of the item you're selecting.
You have to note that if you want to access to a SP file, you have to set your request.credential via :
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
which will take the current credential you're using.
Hope it helps.

Categories