Passing a specific url query param from main url into the iframe url - html

This is what I have.
URL = abc.com/?em=xyz&fn=123
I have an iframe on the page which I want to share some of the param data as follows...
iframe= def.com/xyz
As you can see I just want one of the url params from the main source url to carry across to the iframe, to be part of the url, not an added param on the iframe string. It would always be the single param 'em' that would be carried across, all other params would be ignored.
I think this was clear, but just to show an example of correct iframe = def.com/xyz and wrong would be an iframe with the url = def.com/?em=xyz. I know the latter seems possible in Javascript. I just cannot work out the former. Thanks
Hope someone has any help.
The site is currently on Wordpress if that makes a difference. The iframe url is an external link,not wordpress
Thanks

Right, I have a solution that is working for me so thought I would share. It is important to note that this will probably only work if you are using Wordpress...
Step 1. I created a new page template , called page-iframe php. which references a content file called content-iframe php
In this file I created the iframe code..
<iframe src="domain.com/<?php echo do_shortcode('[urlparam param="em" /]') ?></iframe>
This uses the URL Params Wordpress plugin to read the url and place the param of choice into the iframe which is hard coded into the page template, rather than added in the content/edit area of the wordpress back end.
The only drawback to this as I see it will mean a new page template for every domain you want to use inside the iframe. I only require one domain to be referenced so this is a solution for me.

Purely javascript:
First a function to grab the parameters in the parent URL:
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);
}
Next, call the function to get the 'em' parameter value and store as a variable. Also check that it is defined and not erroneous.
var myParam = getQueryVariable("em");
if ((typeof myParam !== "undefined") && (myParam !== false)) {
Next, create your iframe URL:
var iframeURL = "def.com/".concat(myParam);
Next, assign the iframe URL in your html to this new iframeURL:
document.getElementById('iFrameName').src = iframeURL;
}
Optional; sending the url without an em parameter. You could have done this already in your html.
else{
document.getElementById('iFrameName').src = "http://def.com/";
}
All together:
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);
}
var myParam = getQueryVariable("em");
if ((typeof myParam !== "undefined") && (myParam !== false)) {
var iframeURL = "def.com/".concat(myParam);
document.getElementById('iFrameName').src = iframeURL;
}
else{
document.getElementById('iFrameName').src = "http://def.com/";
}

Related

How to get Chrome and Safari to accept query strings on blobs? [duplicate]

Say I've got a reference to a html file as a Blob b and I create a URL for it, url = URL.createObjectURL(b);.
This gives me something that looks like blob:http%3A//example.com/a0440b61-4850-4568-b6d1-329bae4a3276
I then tried opening this in an <iframe> with a GET parameter ?foo=bar, but it didn't work. How can I pass the parameter?
var html ='<html><head><title>Foo</title></head><body><script>document.body.textContent = window.location.search<\/script></body></html>',
b = new Blob([html], {type: 'text/html'}),
url = URL.createObjectURL(b),
ifrm = document.createElement('iframe');
ifrm.src = url + '?foo=bar';
document.body.appendChild(ifrm);
// expect to see ?foo=bar in <iframe>
DEMO
I don't think adding a query string to the url will work as it essentially changes it to a different url.
However if you simply want to pass parameters you can use the hash to add a fragment to the url
ifrm.src = url + '#foo=bar';
http://jsfiddle.net/thpf584n/1/
For completeness sake, if you want to be able to reference a blob that has as question mark "query string" indicator in it, you can do so in Firefox any way you choose, such as: blob:lalalal?thisworksinfirefox
For Chrome, the above will not work, but this will: blob:lalalla#?thisworksinchromeandfirefox
And for Safari and Microsaft, nothing really works, so do a pre test like so, then plan accordingly:
function initScriptMode() {
var file = new Blob(["test"], {type: "text/javascript"});
var url = URL.createObjectURL(file) + "#test?test";
var request = new XMLHttpRequest();
request.responseType = responseType || "text";
request.open('GET', url);
request.onload = function() {
alert("you can use query strings")
};
try {
request.send();
}
catch(e) {
alert("you can not use query strings")
}
}
If you are doing this with a Javascript Blob for say a WebWorker then you can just to add the parameters into the Blob constructor as a global variable:
const parameters = 'parameters = ' + JSON.stringify({foo:'bar'});
const body = response.body; // From some previous HTTP request
const blob = new Blob([parameters, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));
Or more general case just store the original URL on the location object
const location = 'location.originalHref = "' + url + '";';
const body = response.body; // From some previous HTTP request
const blob = new Blob([location, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));
You could also do this with HTML if you can add them say to the root <HTML> tag as attributes or use the <BASE> element for the url or insert them as a script tag but this would require you to modify the response HTML rather then just prepend some extra data

HTML Use Current page end of URL in target url

long time reader, first time submitter
It looks like i have the ability to insert javascript or HTML in this custom code box, but If it can be done using hTML that would be preferred.
I am trying to get the last string 'Variablex1x' which is dynamic based on the page being viewed. It is a unique identifier that corresponds to records on a different site. I would like to 'grab' that identifier and post it on the end of the target URL. When the user clicks the 'targetdomain.com' url, they are taken to the page of the targetdomain.com/Variablex1x
https://currentdomain.com/portal/x/mycase/Variablex1x
https://Targetdomain.com/Variablex1x
You can try something like this:
$( "#target" ).click(function() {
var Variablex1x;
var newUrl;
Variablex1x = getQueryVariable(nameofvariable)
if(Variablex1x != false){
window.location.href = newurl + "/" + Variablex1x; + "/" + Variablex1x;
}
else{
window.location.href = newurl;
}
});
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);
}
getQueryVariable comes from
https://css-tricks.com/snippets/javascript/get-url-variables/ and will work as long as you know what variable you're looking for.
The idea is when you click on the link instead of actually navigating you'll fire the click function, so you'll need to update the target id. The click function will figure out if you have parameters or not, if you do it will append them to the URL and navigate, if not it will just navigate.
This is not a perfect solution but it should get you started.
IF you don't know what parameters you're looking for here is an answer of how to get those parameters: How can I get query string values in JavaScript?

Safe getElementById or try to determine if ID exists in GUI

Method UiInstance.getElementById(ID) always returns GenericWidget object, even if ID does not exist.
Is there some way how to find out that returned object does not exist in my app, or check whether UI contains object with given ID?
Solution for UI created with GUI builder:
function getSafeElement(app, txtID) {
var elem = app.getElementById(txtID);
var bExists = elem != null && Object.keys(elem).length < 100;
return bExists ? elem : null;
}
It returns null if ID does not exist. I didn't test all widgets for keys length boundary, so be careful and test it with your GUI.
EDIT: This solution works only within doGet() function. It does not work in server handlers, so in this case use it in combination with #corey-g answer.
This will only work in the same execution that you created the widget in, and not in a subsequent event handler where you retrieve the widget, because in that case everything is a GenericWidget whether or not it exists.
You can see for yourself that the solution fails:
function doGet() {
var app = UiApp.createApplication();
app.add(app.createButton().setId("control").addClickHandler(
app.createServerHandler("clicked")));
app.add(app.createLabel(exists(app)));
return app;
}
function clicked() {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(exists(app)));
return app;
}
function exists(app) {
var control = app.getElementById("control");
return control != null && Object.keys(control).length < 100;
}
The app will first print 'true', but on the click handler it will print 'false' for the same widget.
This is by design; a GenericWidget is a "pointer" of sorts to a widget in the browser. We don't keep track of what widgets you have created, to reduce data transfer and latency between the browser and your script (otherwise we'd have to send up a long list of what widgets exist on every event handler). You are supposed to keep track of what you've created and only "ask" for widgets that you already know exist (and that you already know the "real" type of).
If you really want to keep track of what widgets exist, you have two main options. The first is to log entries into ScriptDb as you create widgets, and then look them up afterwards. Something like this:
function doGet() {
var app = UiApp.createApplication();
var db = ScriptDb.getMyDb();
// You'd need to clear out old entries here... ignoring that for now
app.add(app.createButton().setId('foo')
.addClickHandler(app.createServerHandler("clicked")));
db.save({id: 'foo', type: 'button'});
app.add(app.createButton().setId('bar'));
db.save({id: 'bar', type: 'button'});
return app
}
Then in a handler you can look up what's there:
function clicked() {
var db = ScriptDb.getMyDb();
var widgets = db.query({}); // all widgets
var button = db.query({type: 'button'}); // all buttons
var foo = db.query({id: 'foo'}); // widget with id foo
}
Alternatively, you can do this purely in UiApp by making use of tags
function doGet() {
var app = UiApp.createApplication();
var root = app.createFlowPanel(); // need a root panel
// tag just needs to exist; value is irrelevant.
var button1 = app.createButton().setId('button1').setTag("");
var button2 = app.createButton().setId('button2').setTag("");
// Add root as a callback element to any server handler
// that needs to know if widgets exist
button1.addClickHandler(app.createServerHandler("clicked")
.addCallbackElement(root));
root.add(button1).add(button2);
app.add(root);
return app;
}
function clicked(e) {
throw "\n" +
"button1 " + (e.parameter["button1_tag"] === "") + "\n" +
"button2 " + (e.parameter["button2_tag"] === "") + "\n" +
"button3 " + (e.parameter["button3_tag"] === "");
}
This will throw:
button1 true
button2 true
button3 false
because buttons 1 and 2 exist but 3 doesn't. You can get fancier by storing the type in the tag, but this suffices to check for widget existence. It works because all children of the root get added as callback elements, and the tags for all callback elements are sent up with the handler. Note that this is as expensive as it sounds and for an app with a huge amount of widgets could potentially impact performance, although it's probably ok in many cases especially if you only add the root as a callback element to handlers that actually need to verify the existence of arbitrary widgets.
My initial solution is wrong, because it returns false exist controls.
A solution, based on Corey's answer, is to add the setTag("") method and here is ready to use code. It is suitable for event handlers only, because uses tags.
function doGet() {
var app = UiApp.createApplication();
var btn01 = app.createButton("control01").setId("control01").setTag("");
var btn02 = app.createButton("control02").setId("control02").setTag("");
var handler = app.createServerHandler("clicked");
handler.addCallbackElement(btn01);
handler.addCallbackElement(btn02);
btn01.addClickHandler(handler);
btn02.addClickHandler(handler);
app.add(btn01);
app.add(btn02);
return app;
}
function clicked(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel("control01 - " + controlExists(e, "control01")));
app.add(app.createLabel("control02 - " + controlExists(e, "control02")));
app.add(app.createLabel("fake - " + controlExists(e, "fake")));
return app;
}
function controlExists(e, controlName) {
return e.parameter[controlName + "_tag"] != null;
}

Google Apps Script, HTML addClickHandler ServerHandler does NOT work

Can anyone confirm that HTML widgets accept ClickHandlers on the Server side ? I can't get my below code to work.
I create a serverHandler (and for good measure I have even added a useless callback element). Subsequently, I add it to a HTML.addClickHander (for good measure I have even added it to .addMouseUpHandler as well). The function is NOT executed.
var mouseclick = app.createServerHandler("handleTrainingClick_").addCallbackElement(lstFilter);
var params = [ "fromOrg", "trainingTitle", "dueDate", "medical", "status" ];
var resultSet = blSelectActiveTrainings_();
while (resultSet.hasNext()) {
var training = resultSet.next();
var html = TRAINING_ROW;
for (var pI in params) {
html = html.replace("$"+params[pI], training[params[pI]]);
}
pnlList.add(app.createHTML(html).setId(training.id).addClickHandler(mouseclick).addMouseUpHandler(mouseclick)
.addMouseMoveHandler(mousemove).addMouseOutHandler(mouseout).addMouseOverHandler(mouseover));
}
function handleTrainingClick_(e) {
Logger.log(e.source);
var app = UiApp.getActiveApplication();
return app;
}
HTML widgets server side handlers work just fine. It was an incorrect reference in my code. Thanks all.

How to assign URLVariables result to a String Variable?

In the following example (yes, I am coding on my timeline while I try to work this out - I know, I know) I am loading an SWF in an HTML page and then directing the SWF to get the query parameters from the current URL. The query parameter will contain the source for the video to play.
This seems straight forward to me but I cannot get myURL = urlVars.videoloc; to work. More specifically, urlVars.videoloc seems to be undefined rather than holding the query parameter from the URL. All other variables are correct; both wholeURL and urlVars are defined.
//Initialize Global Event Listener
player.addEventListener(Event.ADDED_TO_STAGE, getPlay, false, 0, true);
//Function to play the video
function getPlay(e:Event):void {
var wholeURL:String = ExternalInterface.call("window.location.search.toString");
var urlVars:URLVariables = new URLVariables(wholeURL);
var myURL:String = urlVars.videoloc; //<--- Trouble, returning 'undefined'
errorBox.text = "videoloc="+urlVars.videoloc+"\nwholeURL="+wholeURL+"\nurlVars="+urlVars+"\nmyURL="+myURL; //<--- The reason I know it is returning 'undefined'
if (myURL) {
player.load(myURL);
player.play();
}
}
Ideally you should use a debugger to inspect the makeup of your URLVariables object.
If you're unable to do things the easy way, you could do this to trace its contents:
for (var parameter:String in urlVars) {
trace(parameter + "=" + urlVars[parameter]);
}
As you can see, you can step through every parameter inside urlVars using a for in loop.
I'm guessing videoLoc is your first parameter? Look at the results of this test of mine:
var address:String = "http://www.google.ca/search?q=test&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a";
var urlVars:URLVariables = new URLVariables(address);
for (var parameter:String in urlVars) {
trace(parameter + "=" + urlVars[parameter]);
}
The output of this is:
aq=t
rls=org.mozilla:en-GB:official
client=firefox-a
http://www.google.ca/search?q=test
ie=utf-8
oe=utf-8
See what happened to the q parameter? To fix this, use only the text past the ?
var address:String = "http://www.google.ca/search?q=test&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a";
var urlVars:URLVariables
= new URLVariables(address.substr(address.indexOf('?')+1));
for (var parameter:String in urlVars) {
trace(parameter + "=" + urlVars[parameter]);
}