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] + "&";
}
}
Related
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'))
Im giving my users the possibility to filter products without refreshing the page with ajax. i update the url to make it look like :
http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4
where the int values are id's split by -.
so i have the options:
style
price
brand
color
what i want is get these values in a var for each filter option so that i end with :
var styleValues = 7,1,2
var priceValues = 4,5,7
if only price filter is selected the url will look like
http://mywebsite.com/products/filter?price=4-5-7
so i cant split on the tags for the filters.
I really like to know what would be the best way to turn the url to different vars.
What i already know :
how to get the filter part:
var filterPart =window.location.search;
Great article on css tricks covering just this:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
window.location.protocol = "http:"
window.location.host = "css-tricks.com"
window.location.pathname = "example/index.html"
So to get the full URL path in JavaScript:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, you can split the string on "/" characters
var pathArray = window.location.pathname.split( '/' );
Then access the different parts by the parts of the array, like
var secondLevelLocation = pathArray[0];
To put that pathname back together, you can stitch together the array and put the "/"'s back in:
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "/";
newPathname += pathArray[i];
}
Or like this::
http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
maybe this can help you :
var Request = {
QueryString : function (item) {
var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
return svalue?svalue[1]:svalue;
},
queryAllString : function() {
var urlLocation = location.href;
var startPosition = urlLocation.indexOf("?");
if (startPosition < 0) {
return '';
} else {
return urlLocation.slice(startPosition);
}
}
}
If you want to get price,you can do like this:
Request.QueryString("price")
My own take on this problem would be:
// this is simply to compensate for the lack of a current document.location to search:
var documentURL = 'http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4',
tempA = document.createElement('a');
tempA.href = documentURL
var searches = {
'get': function() {
var queries = {
// a cache of all named parameters found:
'found': []
},
// stripping off the leading '?':
queryString = tempA.search.substring(1),
// getting the key-value pairs:
keyValues = queryString.split('&'),
// to be used withi the forEach():
pair;
keyValues.forEach(function(el) {
// creating an array consisting of the keyName and keyValue:
pair = el.split('=');
// if we have both a name and a value we proceed:
if (pair.length === 2) {
if (!queries[pair[0]]) {
// if there is no present entry for the current key, we:
// push the key to the 'found' array, and
// create a record in the queries object for that key
// containing an array of the found values:
queries.found.push(pair[0]);
queries[pair[0]] = pair[1].split('-');
} else {
// otherwise (there is an existing key in the queries object),
// we push the values to the end of the existing array:
queries[pair[0]].push(pair[1])
}
}
});
return queries;
}
};
var cachedSearches = searches.get(),
allKeys = cachedSearches.found;
allKeys.forEach(function(el){
console.log(el, cachedSearches[el], cachedSearches[el].join(', '));
});
References:
Array.prototype.forEach().
Array.prototype.join().
String.prototype.split().
Try
var filtered = {};
var url = "http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4";
var filters = url.split("?")[1].split("&");
filters.map(function(val) {
filtered[val.split("=")[0]] = val.split("=")[1].split("-").join(",")
});
console.log(filtered);
var filtered = {};
var url = "http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4";
var filters = url.split("?")[1].split("&");
filters.map(function(val, i) {
filtered[val.split("=")[0]] = val.split("=")[1].split("-").join(",");
document.body.innerText += (Object.keys(filtered)[i].toString() +": "+ filtered[val.split("=")[0]]) + "\n"
});
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;
}
I am trying to getElementById("game_image") and the TagName is 'img' I want the data within the 'src' tag, specifically the 'key=f430a2c1' token.:
<img id="game_image" src="img/index.php?key=f430a2c1&rand=956875" alt="game image." style="padding-right:150px;" />
*
$("#b_hint").click(function(){
// var images = document.getElementsByTagName("img"),
// wanted;
var data = document.getElementById("game_image"), wanted;
wanted = data[1].src;
// if (images.length) {
// wanted = images[1].src;
// if (wanted) {
// wanted = wanted.split("?");
// if (wanted.length >= 2 && wanted[1].indexOf("&") !== -1) {
// wanted = wanted[1].split("&")[0];
// }
// }
//}
//if (typeof wanted !== "string") {
// wanted = "";
// }
alert(wanted);
wanted = data.src;
getElementById returns a single element, not a NodeList, so you don't need to use array syntax.
wanted = data.src;
wanted = wanted.substring(wanted.indexOf('?') + 1)
Taking into account the the src URL could contain more parameters separated by '&', you can extract key=... like this:
function getKey(url) {
var idx1 = url.indexOf("?") + 1;
if (idx1 == -1) { return ""; }
var idx2 = url.indexOf("&");
if (idx2 == -1) { idx2 = url.length; }
return url.substring(idx1, idx2);
}
$("#b_hint").click(function() {
var img = document.getElementById("game_image");
var wanted = getKey(img.src);
...
NOTE:
For the getKey() function to work properly, the 'key' parameter must come straight ater the '?' (e.g. ...?key=..., but not ...?some=other&key=...).
See also this regex-powered solution:
var regex = new RegExp(".*?\\?.*?\\b(key=[^&]+)");
$("#b_hint").click(function() {
var src = document.getElementById("game_image").src;
var wanted = regex.test(src) ? src.match(regex)[1] : "";
...
This will properly match the key=<value> part, even if 'key' is not the first parameter in the query string.
Jquery?!
working fiddle -> http://jsfiddle.net/mpyfQ/8/
var data = $("#game_image").attr("src");
data = data.substring(data.indexOf('?') + 1);
The answer should be InnerHTML.
var test = "http://www.example.org/search?q=whatever&another=moretext";
How can I extract another's value (moretext) in the query string above and make a variable out of it?
var test = "http://www.example.org/search?q=whatever&another=moretext";
var another = test.split('another=');
another is an array with another[0] = 'http://www.example.org/search?q=whatever&' and another[1] = 'moretext'.
keep this function in your bag :
function querySt(qsName, url)
{
var theUrl;
if (url == null || url == undefined)
theUrl = window.location.search.substring(1); else theUrl = url;
var g = theUrl.split("&");
for (var i = 0; i < g.length; i++) {
var pair = g[i].split("=");
if (pair[0].toLowerCase() == qsName.toLowerCase())
{
return pair[1];
}
}
return null;
}
Usages
alert(querySt("another")+' '+querySt("q"));