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.
Related
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.
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
I've written a script that detects the referring URL from a couple of search engines and then passes this value (not the mc_u20 variable) to a server to be used somewhere. The script works like a treat except for one big problem, it simply won't track Google search results. So any result that comes from Google, simply doesn't register. Here is the script:
var mc_searchProviders = {"search_google":"google.co","search_bing":"bing.com","search_msn":"search.msn","search_yahoo":"search.yahoo","search_mywebsearch":"mywebsearch.com","search_aol":"search.aol.co", "search_baidu":"baidu.co","search_yandex":"yandex.com"};
var mc_socialNetworks = {"social_facebook":"facebook.co","social_twitter":"twitter.co","social_google":"plus.google."};
var mc_pageURL = window.location +'';
var mc_refURL = document.referrer +'';
function mc_excludeList() {
if (mc_refURL.search('some URL') != -1) {
return false; //exclude some URL
}
if (mc_refURL.search('mail.google.') != -1) {
return false; //exclude Gmail
}
if (mc_refURL.search(mc_paidSearch) != -1) {
return false; //exclude paidsearch
}
else {
mc_checkURL();
}
}
mc_excludeList();
function mc_checkURL() {
var mc_urlLists = [mc_searchProviders, mc_socialNetworks],
i,mc_u20;
for (i = 0; i < mc_urlLists.length; i++) {
for (mc_u20 in mc_urlLists[i]) {
if(!mc_urlLists[i].hasOwnProperty(mc_u20))
continue;
if (mc_refURL.search(mc_urlLists[i][mc_u20]) != -1) {
mc_trackerReport(mc_u20);
return false;
}
else if ((mc_refURL == '') && (mc_directTracking === true)){
mc_u20 = "direct_traffic";
mc_trackerReport(mc_u20);
return false;
}
}
}
}
The most annoying thing is, I have tested this on my local machine (by populating the mc_refURL with an actual google search URL and it works like a charm. I've also thought that maybe when searching through the first mc_searchProviders object it is somehow skipping the first instance, so I added a blank one. But still this doesn't work. What's even more annoying is that for every other search engine, the mc_u20 variable seems to populate with what I need.
This is driving me insane. Can anyone see what's wrong here? I might also mention that I'm signed into Google but I don't see how this would affect the script as their blogpost (in November) said they were filtering keywords not stopping the referring URL from being passed.
Right so I figured out what was going on. The first part of the script excludes your own URL (see where it says 'some URL'. Say this was set to www.example.com. In Google if I searched for say example and Google returned www.example.com as the first search result, in the referring URL it would contain www.example.com. Hence why the script was breaking, maybe someone will find this useful in future.
I use document.URL to detect if a user is on index.html:
if(document.URL.indexOf("index") >-1) return true;
But if the user types "mydomain.com" or "mydomain.com/" then the test returns false.
I could try:
if(document.URL ==="http://myDomain.com") return true;
But I want to use this code on different domains. Any suggestions?
There are so many permutations of URL that could mean that a user is on index.html. Instead could you not put a var within that file:
<script type="text/javascript">
on_index = true;
</script>
Just check if on_index is not undefined and is true. That'll be accurate 100% of the time.
javascript Location object has many useful properties, in particular, you can examine location.pathname.
Basically, you're on the "index" page if the pathname is 1) empty 2) is equal to a slash / 3) starts with index or /index.
var p = window.location.pathname;
if (p.length === 0 || p === "/" || p.match(/^\/?index/))
alert ("on the index page!")
See Javascript .pathname IE quirk? for the discussion of leading slash issues.
There isn't a direct link between files and URLs. Additionally, index.html does not need to be in the site's root and the default page does not need to be index.html.
If you want a generic solution, you're probably out of luck. If you want a solution for your particular case, you can just provide that info from the page itself, e.g. defining an ID or class name:
<body class="index">
... or a JavaScript variable:
// Pick one
var page = 'index';
var isIndex = true;
If all you want is some simple string manipulation with current location, grab the pathname property of the window.location object:
// Untested
if( window.location.pathname=="/" || window.location.pathname=="/index.html" ){
}
You could use
if (document.location.pathname === '/' ||
document.location.pathname.indexOf('index') >-1 ) {
return true;
}
If you have access to the actual page and not just the script then you should follow #Ben Everard's advice.
Just make sure you include the snippet he proposes before your script..
I've made a general hash up of the following function. Basically linking this function to the onclick method of a button. The idea being that if the next page/div is visible to navigate there else navigate to the next one, and so on. If there are no further pages visible (from the current page) then alert the user. Just in case they carry on clicking.
Here is my code:
function showNext(id){
var currPage = id.match(/\d+/)-1;
var pages = [document.getElementById("page2"),document.getElementById("page3"),document.getElementById("page4")];
var next = ["page2marker","page3marker","page4marker"];
var valid = false;
for (var i=currPage; i<=pages.length; i++){
var Icansee = pages.some(function() { pages[i].style.display == "block"});
if(Icansee){
valid = true
}
if(valid){
return window.location.hash = next[i];
}
if(!valid){
alert("No other pages to navigate to");
}
}
}
I know that my use of the array some function is incorrect, along with plenty of other things. Just need a general shove in the right direction.
Edit: Just realised that array some is an ECMAScript 5 addition which isn't supported by the piece of software that I'm using. So I will need to find another way of solving this one. Any ideas?
There's a sample implementation of Array.prototype.some for browsers that don't support it natively at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some