Is there a simple way to have a local webpage display a variable passed in the URL? - html

I am experimenting with a Firefox extension that will load an arbitrary URL (only via HTTP or HTTPS) when certain conditions are met.
With certain conditions, I just want to display a message instead of requesting a URL from the internet.
I was thinking about simply hosting a local webpage that would display the message. The catch is that the message needs to include a variable.
Is there a simple way to craft a local web page so that it can display a variable passed to it in the URL? I would prefer to just use HTML and CSS, but adding a little inline javascript would be okay if absolutely needed.
As a simple example, when the extension calls something like:
folder/messageoutput.html?t=Text%20to%20display
I would like to see:
Message: Text to display
shown in the browser's viewport.

You can use the "search" property of the Location object to extract the variables from the end of your URL:
var a = window.location.search;
In your example, a will equal "?t=Text%20to%20display".
Next, you will want to strip the leading question mark from the beginning of the string. The if statement is just in case the browser doesn't include it in the search property:
var s = a.substr(0, 1);
if(s == "?"){s = substr(1);}
Just in case you get a URL with more than one variable, you may want to split the query string at ampersands to produce an array of name-value pair strings:
var R = s.split("&");
Next, split the name-value pair strings at the equal sign to separate the name from the value. Store the name as the key to an array, and the value as the array value corresponding to the key:
var L = R.length;
var NVP = new Array();
var temp = new Array();
for(var i = 0; i < L; i++){
temp = R[i].split("=");
NVP[temp[0]] = temp[1];
}
Almost done. Get the value with the name "t":
var t = NVP['t'];
Last, insert the variable text into the document. A simple example (that will need to be tweaked to match your document structure) is:
var containingDiv = document.getElementById("divToShowMessage");
var tn = document.createTextNode(t);
containingDiv.appendChild(tn);

getArg('t');
function getArg(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

Related

Making a simple flexible translate function in nodejs

In nodejs I have these (very long) translation files
gb.json (english)
{
"transHi":"Hello",
"transBye":"Goodbye"
}
de.json (german)
{
"transHi":"Gutentag",
"transBye":"Auf Wiedersehen"
}
I have a lot of controllers that all need these texts available in the many languages so I can call them when ever needed.
The obvious way would be something like this in my app.js:
global.gb = require('../global/language/gb.json');
global.de = require('../global/language/de.json');
And when I need a text I would call like:
myText = global.gb.transHi
myText = global.de.transHi
But!! the language is always determined by a variable
usersLanguage = "de"
myText = global.usersLanguage.transHi
And that wont work.
I also tried:
usersLanguage = "de"
myText = global.usersLanguage.transHi
Perhaps I could solve it with a function that has a long switch structure
var findText = (language,textkey) => {
switch(language) {
case "gb:
return gb.textkey
break;
case "de:
return de.textkey
break;
}
}
myText = translate(usersLanguage, "transHi");
But I cant seem to make that work either.
How would I do this in a simple and flexible way?
UPDATE: Is it possible to do this?
Any object property accessed via . can also be accessed using array index notation []. So,
var langObj = texts.gb;
is the same as
var langObj = texts["gb"];
which is also the same as
var lang = "gb";
var langObj = texts[lang];
Same for the textkey, using the .textkey you get the property called textkey, which probably doesn't exist. If you want a different property depending on the value of the variable textkey, do
var text = langObj[textkey];

Search viewer model by attribute names

I followed this Search demo, and am trying to expand it to only search on specified attribute names.
It works without an attribute name, and returns an array of matching ids. But if I supply anything for the attribute name then search returns an empty array. I am guessing I need some magic formating for the attribute name.
So currently I have:
function search() {
var txtArea = document.getElementById("TextAreaResult");
var searchStr = document.getElementById("SearchString").value;
var searchProperties = document.getElementById("SearchProperties").value;
if (searchStr.length == 0) {
txtArea.value = "no search string.";
return;
}
var viewer = viewerApp.getCurrentViewer();
viewer.clearSelection();
if (searchProperties.length == 0)
viewer.search(searchStr, searchCallback, searchErrorCallback);
else {
var searchPropList = searchProperties.split(',');
viewer.search(searchStr, searchCallback, searchErrorCallback, searchPropList);
}
}
where searchProperties is a user input, eg "Name", and searchPropList becomes a single element array.
The same example also covers getProperties(), which returns displayName and displayCategory for each property, but I don't see a separate internal name.
Am I missing something obvious from here or do I need to transform "Name" in some way.
Or does someone have an example that will list the true name rather than displayName?
The Autodesk.Viewing.Viewer3D.search() method is NOT case sensitive on the text parameter, but it IS case sensitive on the attributeNames parameter, and you need to use the full name of the attribute.
We're now (Aug, 25, 2016) updating the documentation.

Need to alter space from postal code in results array

Hi my requirement need to get postal code from
var address= results[0].formatted_address ;
this formatted value.
Because nether land address have "Danzigerkade 12,1013 AP Amsterdam,Netherlands" this kind of address. but i don't want postal code like this"1013 AP" . i need "1013AP" like this.
Please give me the solution.
Thanks in advance.
I don't recommend parsing the formatted_address to get the postal code or any other specific address fields. Instead, you should scan through the address_components and check the types array of each one to find the address field you need. This is much more reliable than parsing the formatted string.
Once you have the postal code, removing the space is trivial.
To find the postal code for an entry in your results array (e.g. results[0]), you can use code like this:
function getAddressComponent( result, type ) {
var components = result.address_components;
for( var i = 0; i < components.length; ++i ) {
var component = components[i], types = component.types;
for( var k = 0; k < types.length; ++k ) {
if( types[k] == type ){
return component;
}
}
}
return {};
}
var component = getAddressComponent( results[0], 'postal_code' );
var postalCode = component ? component.short_name : '';
var postalCodeNoSpace = postalCode.replace( ' ', '' );
console.log( postalCodeNoSpace );
Update in reply to your comment:
The code you're asking about with ? and : uses the conditional operator found in JavaScript and many other languages:
var postalCode = component ? component.short_name : '';
That works just like this longer form that should look more familiar:
if( component )
postalCode = component.short_name;
else
postalCode = '';
The idea was to not try to reference component.short_name if component itself is null or undefined, because of course that would be an error. In other words, to protect the program from crashing if getAddressComponent() does not find a postal code.
But interestingly enough, there's a bug in the way I was using it. Look at the last line of getAddressComponent():
return {};
Originally I was going to return null there - and then the code you asked about would have been correct - but for some reason I decided to return an empty object instead. So the code in question wasn't quite right with that change.
One way to fix this would be to go back to what I originally meant to do, and change the last line of getAddressComponent() from this:
return {};
to:
return null;

Issue with OAuth and Flickr - cannot request token

I am currently trying to request a token from Flickr to then be able to do some calls to their OAuth methods. I know I must be doing something wrong, for I get a reply that the signature is wrong, but honestly I followed their instructions (http://www.flickr.com/services/api/auth.oauth.html, http://www.flickr.com/services/api/auth.oauth.html#request_token, http://www.flickr.com/services/api/flickr.auth.oauth.getAccessToken.html) but I still get an error:
oauth_problem=signature_invalid&debug_sbs=GET&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token&oauth_callback%3D%26oauth_consumer_key%3Da0f20d2c9b0a142848cffdf9d9a5ad78%26oauth_nonce%3DFCBB713F-581E-4BC6-42FF-C50252D839EC%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1330450158%26oauth_version%3D1.0
I don't get how to create that signature nor how to put it in the request, could anybody point me in the right direction? Thanks!
I am currently working with AS3, below is my code:
// request params
var now:Date = new Date();
var requestParams:Object = {};
requestParams.oauth_callback = ""; // there is no callback, it's a desktop application
requestParams.oauth_consumer_key = API_KEY;
requestParams.oauth_nonce = UIDUtil.getUID(now);
requestParams.oauth_timestamp = String(now.time).substring(0, 10);
requestParams.oauth_signature_method = "HMAC-SHA1";
requestParams.oauth_version = "1.0";
// create an array to sort param names alphabetically
// mandatory to create signature
var sortedRequestParamNames:Array = [];
var name:String;
for(name in requestParams)
{
sortedRequestParamNames.push(name);
}
sortedRequestParamNames.sort();
// create signature
// see http://www.flickr.com/services/api/auth.spec.html#signing
var oauthSignature:String = API_SECRET;
var i:uint;
var numParams:uint = sortedRequestParamNames.length;
var paramName:String;
for(i = 0; i < numParams; i++)
{
paramName = sortedRequestParamNames[i];
oauthSignature += paramName + convertToPercentEntities(requestParams[paramName]);
}
oauthSignature = MD5.hash(oauthSignature);
// build request
var tokenRequestString:String = REQUEST_TOKEN_URL;
for(i = 0; i < numParams; i++)
{
paramName = sortedRequestParamNames[i];
tokenRequestString += (i == 0) ? "?" : "&";
tokenRequestString += paramName + "=" + requestParams[paramName];
}
tokenRequestString += "&oauth_signature=" + oauthSignature;
var tokenRequest:URLRequest = new URLRequest(tokenRequestString);
tokenRequest.method = URLRequestMethod.GET;
// load request
initLoader();
_loader.addEventListener(Event.COMPLETE, requestTokenLoadedHandler);
_loader.load(tokenRequest);
Basically, you need to use the HMAC-SHA1 algorithm instead of an MD5. I'll walk you through it.
1. Create the signature base string
You seem to be doing that (but you are assigning it directly to the signature variable). Compiling the base string is done by concatenating three different parts.
Convert the HTTP Method to uppercase and set the base string equal to this value. Example: GET
Append the '&' character to the base string.
Percent encode the URL (without parameters) and append it to the base string. Example: http%3A%2F%2Fexample.com%2Frequest
Append the '&' character to the base string.
Percent encode the sorted parameter string and append it to the base string.
It should end up looking like this:
GET&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q
%26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_
key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_m
ethod%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk
9d7dh3k39sj
Now you're done with the signature base string. Lets move on to
2. Figuring out your signing key.
Your signing key is on this format: CONSUMER_SECRET + "&" + TOKEN_SECRET. But since you do not have a token yet, the signing key is the consumer secret and an ampersand. Like this: CONSUMER_SECRET + "&".
For all requests, except the first one your will have a token though, either a request token or an access token.
3. Combine the key and the base string using the HMAC-SHA1 algorithm.
I have used http://code.google.com/p/as3crypto/ when signing with AS3. You can even test its HMAC-SHA1 algorithm on this demo page: http://crypto.hurlant.com/demo/.
Use the base string as input, and the signing key as key to the HMAC-SHA1 algorithm.
The output of the HMAC-SHA1 algorithme will be a binary string which needs to be base64 encoded to produce the final signature. It should look something like this:
NYIQGEwIomgCuVOIA28pMDMID78=
This should be send with the request as the oauth_signature parameter.
I had problem with it too, ended up using FlickrNet API.
http://flickrnet.codeplex.com/

Select statement selection through URL parameters

I'm attempting to alter the contents of certain parts of a HTML form through usage of the URL. For a text field, I'm aware that this will suffice,
http://<domain>?fieldname=ping&anotherfield=pong
On the form there are multiple select braces (drop down boxes); Is it possible to pick an int or string value through the url for this?
There seems to be little documentation on this (or even people trying to do the same)...
You haven't specified how you want to do this, but I'll assume that you want to use JavaScript:
To get a value from QueryString:
getQueryStringArgument = function(key) {
var hu = window.location.search.substring(1);
var gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
var ft = gy[i].split("=");
if (ft[0] == key)
return ft[1];
}
}
To set the selected value of the select list:
document.getElementById("sel").value = getQueryStringArgument("id");
For a text field, I'm aware that this will suffice
No, it won't (at least, not in a generic way).
For a text field, the default value is specified by the value attribute. There might be a server side script that populates it based on query string data, but there doesn't have to be.
On the form there are multiple select braces (drop down boxes); Is it possible to pick an int or string value through the url for this?
Again, this requires an attribute to be set (selected on <option>), and that could (again) be set by a server side script based on the query string data.