HTML Use Current page end of URL in target url - html

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?

Related

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

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/";
}

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

Repeatedly Grab DOM in Chrome Extension

I'm trying to teach myself how to write Chrome extensions and ran into a snag when I realized that my jQuery was breaking because it was getting information from the extension page itself and not the tab's current page like I had expected.
Quick summary, my sample extension will refresh the page every x seconds, look at the contents/DOM, and then do some stuff with it. The first and last parts are fine, but getting the DOM from the page that I'm on has proven very difficult, and the documentation hasn't been terribly helpful for me.
You can see the code that I have so far at these links:
Current manifest
Current js script
Current popup.html
If I want to have the ability to grab the DOM on each cycle of my setInterval call, what more needs to be done? I know that, for example, I'll need to have a content script. But do I also need to specify a background page in my manifest? Where do I need to call the content script within my extension? What's the easiest/best way to have it communicate with my current js file on each reload? Will my content script also be expecting me to use jQuery?
I know that these questions are basic and will seem trivial to me in retrospect, but they've really been a headache trying to explore completely on my own. Thanks in advance.
In order to access the web-pages DOM you'll need to programmatically inject some code into it (using chrome.tabs.executeScript()).
That said, although it is possible to grab the DOM as a string, pass it back to your popup, load it into a new element and look for what ever you want, this is a really bad approach (for various reasons).
The best option (in terms of efficiency and accuracy) is to do the processing in web-page itself and then pass just the results back to the popup. Note that in order to be able to inject code into a web-page, you have to include the corresponding host match pattern in your permissions property in manifest.
What I describe above can be achieved like this:
editorMarket.js
var refresherID = 0;
var currentID = 0;
$(document).ready(function(){
$('.start-button').click(function(){
oldGroupedHTML = null;
oldIndividualHTML = null;
chrome.tabs.query({ active: true }, function(tabs) {
if (tabs.length === 0) {
return;
}
currentID = tabs[0].id;
refresherID = setInterval(function() {
chrome.tabs.reload(currentID, { bypassCache: true }, function() {
chrome.tabs.executeScript(currentID, {
file: 'content.js',
runAt: 'document_idle',
allFrames: false
}, function(results) {
if (chrome.runtime.lastError) {
alert('ERROR:\n' + chrome.runtime.lastError.message);
return;
} else if (results.length === 0) {
alert('ERROR: No results !');
return;
}
var nIndyJobs = results[0].nIndyJobs;
var nGroupJobs = results[0].nGroupJobs;
$('.lt').text('Indy: ' + nIndyJobs + '; '
+ 'Grouped: ' + nGroupJobs);
});
});
}, 5000);
});
});
$('.stop-button').click(function(){
clearInterval(refresherID);
});
});
content.js:
(function() {
function getNumberOfIndividualJobs() {...}
function getNumberOfGroupedJobs() {...}
function comparator(grouped, individual) {
var IndyJobs = getNumberOfIndividualJobs();
var GroupJobs = getNumberOfGroupedJobs();
nIndyJobs = IndyJobs[1];
nGroupJobs = GroupJobs[1];
console.log(GroupJobs);
return {
nIndyJobs: nIndyJobs,
nGroupJobs: nGroupJobs
};
}
var currentGroupedHTML = $(".grouped_jobs").html();
var currentIndividualHTML = $(".individual_jobs").html();
var result = comparator(currentGroupedHTML, currentIndividualHTML);
return result;
})();

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;
}

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]);
}