My Problem is:
I have an eibport:
www.bab-tec.de/
You can See a live demo in the live section.
Now the problem.
I would like to start or run a javascript on this page with entering the url like:
http:// IP-EIBPORT /#javascript:click(Button)
or in another way.
Can someone helps me?
You may want to setup your script to look for a sepcific hash and run a function based on that.
switch(location.hash){
case "#button":
//click button
break;
case "#other":
//do something else
break;
}
Then use urls like /#button or /#other
The way to do exactly what you want is the following, but it's not recommended!
eval(location.hash.substr(1));
Use a url like /#alert('test'); That will work, but it means anyone can link to your site and execute javascript which is a very unsafe thing to do.
You cannot include JavaScript-invoking code in the URL itself. The best you can do is have a script on the destination page that examines the location, and responds accordingly.
As an example, suppose you wanted to expose sum method via the url. If somebody were to load your page with the following query string: ?method=sum¶ms=5,5, you could have logic in place to look for these parts, and process them.
var methods = {
sum: function () {
var result = 0; i = -1;
while ( ++i < arguments.length )
result += parseInt( arguments[i], 10 );
return result;
}
};
var method = location.search.match(/method=(.*)&/)[1],
params = location.search.match(/params=(.*)$/)[1].split(",");
var result = methods[ method ].apply( this, params );
alert( result );
See it in action: http://jsfiddle.net/jonathansampson/TF5ta/show/?method=sum¶ms=5,5
Related
I want to create a script that highlights every instance of a string on a page and that string is received as a get request paramater. I want my page to link to the script like: <script src="../Scripts/highlightSearch.js" defer></script> and inside that script I want to have a function like function highlight(content) {...} where content is the string that I want to be highlighted throughout the page. How can I acess content via my script?
In terms of "reading the GET request" there is a relatively new API available that makes reading the querystring parameters trivial. This particular API is URLSearchParams
If you refer to the compatability table at the bottom you'll notice that Internet Exploder does not support this API so, as a possible alternative, you can use quite a simple function to process the querystring yourself. This following function could ( relatively ) easily be modified to provide similar methods to those found in the URLSearchParams api - alternatively search for a Polyfill
const getArgs=function() {
let o={};
location.search.substring(1).split('&').forEach( function( n ){
let l=n.indexOf('=');
if( ~l )o[ n.substring( 0, l ) ]=unescape( n.substring( l + 1 ) );
});
return o;
};
With those in place when you need to read / mainpulate the querystring you can fork the logic
if( 'URLSearchParams' in window ){ /* use methods available to/within the "URLSearchParams" api */ }
else {
let args=getArgs();
let query=args.hasOwnProperty('keyword') ? args.keyword ? false;
if( query ){
let res=RegExp(pattern[, flags]);
/* etc */
}
}
That should, I hope, help give a baseline with which to accomplish the stated goal - there are other ways open to you young Jedi. Good luck.
I need to read the url using some JS code in order to extract some parameters and execute some tasks depending on them. However I have two problems:
-The webpage is not mine so I cannot modify anything on it or inspect it in great detail. I just write some script that the client load from its webpage, and executes some functions on load. I can modify this script but not anything else.
-In this functions, I save in a variable the window.location.href value, but when doing some logs in order to verify what is reading, I see that the value does not correspond to the actual url in the address bar. Moreover, if I check the value of window.location.href in the browser console, then the value matches with the address bar!
I check this value at the start of my script and at the end and it does not match in any case. I don't know at which point of the loading does my script start execution, and I don't know what is causing this behaviour.
EDIT: Here is some code, I won't show it all as most of it works fine and doesn't have relation to my problem.
This is what I sent to my client to put in its webpage:
var s1 = document.createElement('script');
s1.src = 'source_of_my_script;
document.head.appendChild(s1);
s1.onload = function () {
s();
};
This is part of my script:
function s(){
var my_url_var = window.location.href;
console.log("1st value", my_url_var);
var param = extractParamFromUrl(my_url_var); //this functions get some value written in the url
switch (param){
case 'value_0':
// do things
case 'value_1':
// do other things
defalut:
// do default actions
}
console.log("final value", window.location.href);
}
I cannot show you the exact URLs because of privacy reasons, but they are similar to these ones:
Address bar url (and what i get if I check window.location.href in browser console): https://www.client_dummy_url.com/dummy/cobranded?origin=8000097& ... (more params separated by &)
What I get from window.location.href in script: https://www.client_dummy_url.com/drfd01/main/control.do?action=start&internet=S&app=EP& ... (more params, but not all the ones I want!)
Many thanks!
After some tries, I managed to get it to work with the solution posted by #Vaibhav at Access parent URL from iframe
//var my_url_var = window.location.href;
var my_url_var = (window.location != window.parent.location)
? document.referrer
: document.location.href;
I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.
I am trying to differentiate between different urls. I have an if/else in place but hopefully this can be done better in vanilla js. No express js please.
/product
/product/1
/product/1/customer
/product
/product/2
/product/2/customer
/customer
/customer/1
/customer/1/product
/customer
/customer/2
/customer/2/product
Current strategy:
if(request.url.indexOf('/product') != -1 && request.url.length == '/product'.length) {
} else if { // /product/:id
if(!request.params) request.params = {};
request.params.id = request.url.match(/^\/product\/([^\\/]+?)(?:\/(?=$))?$/i)[1];
} else { // 3rd case /product/1/customer
}
I think my if/else are not resolving to all uri's mentioned above. Please suggest any solution, so that I can resolve all 3 cases from above in a reusable way for different urls, and run appropriate queries from there.
Here is a very basic example that will hopefully put you on the right track. You firstly need to store all the urls you want, and their associated functions that you want to run. Then when a new url comes in, you need to compare it to your stored urls to see if there is a match. As urls can have certain varying values, you need a way to deal with wildcards.
So firstly create a function that adds a particular url scheme, and associated run function to an array.
var myUrls = [];
function addUrl(url, associatedFunc){
mrUrls.push({
func: associatedFunc,
parts: url.split('/').map(function(item){
return item.startsWith(':') ? null : item;
});
});
}
To add a new url you would put : in front of any part of the url that can be wild.
addUlr('/product/:value/customer', doCustomerStuffFunc);
Next you need a way of comparing incoming url requests with your url array.
function resolveUrl(url){
myUrls.forEach(function(item){
var pieces = url.split('/');
if(pieces.length === item.parts.length){
for(var i=0; i<pieces.length; i++){
// check if the piece is valid
if(item.parts[i] && pieces[i] !== item.parts[i]){
break;
}
// if there is an exact match run the function and return
if(i === pieces.length - 1){ return item.func(pieces); }
}
}
});
}
This will run the first encountered matches associated function, passing in an array containing all the values in the given url.
Note: This is untested code, written off the top of my head, intended to get you started, and not be a full solution.
This is the algorithm of what I want to do:
1.Locates flickr links with class' high_res_link and puts them in array [].
2.Opens flickr link with extension "sizes/h/"
3.finds largest photo dimensions on flickr. Then goes to that link. Or if there arent any big enough goes to step 2 and goes to next
array.
4. then opens link to download if downloading is enabled. If not goes to step 2 and goes to next array.
5. Goes to step 2 and goes to next array.
I am trying to write some code that crosses two domains: Tumblr and Flickr.
I have currently written 3 functions with Jquery and Javascript which I want to run on 2 different URLs:
Function #1:
function link_to_flickr() {
var hre = [];
$('.high_res_link').parent(this).each(function(){
var h = $(this).attr('href') +"sizes/o/";
hre.push(h);
});
alert(hre[0]);
}
This finds the links on the Tumblr page to the Flickr pages I want. And puts them in an array.
Function #2:
function find_large_quality() {
var w = 1280;
var h = 720;
var matchingDivs = $("small").each(function () {
var match = /^\((\d+) x (\d+)\)$/.exec($(this).text());
if (match) {
if (parseInt(match[1], 10) >= w && parseInt(match[2], 10) >= h) {
return true;
}
}
return false;
});
var href = $.trim(matchingDivs.text()).match(/\(.*?\)/g);
if (matchingDivs.length >= 1) {
alert("success");
} else {
alert("fail");
}
var ho = $('small:contains("'+href[href.length - 1]+'")').parent(this).find("a").attr("href");
alert("http://www.flickr.com"+ho);
}
This function once on the Flickr URL then searches for an image with dimensions greater than 720p.
Function #3:
function Download(){
var heyho = $('a:contains("Download the")').attr('href');
window.open(heyho, '_blank');
}
This downloads the image file. Once on the Highest quality Flickr URL
Each alert I want to open the URL instead. And perform the next function on. I have been trying for ages and ages of a method to go about doing something like this.
Using AJAX, using PHP, using Jsonp, using jquery.xdomainajax.js, etc... But I can't come up with a sufficient method on my own.
Has anybody got any way they would recommend going about doing something like this?
You usually can't run functions on different domains due to CORS unless the domains allow that.
If you're writing a userscript/extension, what you can do is use postMessage (quick tutorial on how to use it cross-domain) on both pages in a content script and use the achieved inter-page communication to control your script flow.
An alternate method is to use the APIs of the websites you want to access.
Or use Python with BeautifulSoup.