Get requested URL in Javascript - javascript

I need to find the requested URL in Javascript (not the current URL) to identify which of two displayed sites is loaded.
Scenario: I'm currently building a module for the Icinga Web 2 which has the option the show two frames (two separate .phtml files) side by side. When two of these frames are open, the URL shown in the browser looks as follows:
http://host/icingaweb/mymodule/siteA#!/icingaweb/mymodule/siteB
You can reload the single frames separately by clicking a button on it. In the browser log (and apache log) you can see, that for each load just the specific page is requested:
// reloading siteA
GET http://host/icingaweb/mymodule/siteA
// reloading siteB
GET http://host/icingaweb/mymodule/siteB
I need exactly this single request in Javascript (at least the requested site).
Unfortunately the following functions do not work:
var pathname = window.location.pathname;
// returns (no matter which site is reloaded): "/icingaweb/mymodule/siteA"
var url = window.location.href;
// returns (no matter which site is reloaded): "http://host/icingaweb/mymodule/siteA#!/icingaweb/mymodule/siteB"
The Icinga Web 2 parses all javascript content to a single file which is afterwards globally accessible (icinga.min.js). Custom javascript has to be put in the module.js.
module.js
(function(Icinga) {
var mymodule = function(module) {
/**
* The Icinga.Module instance (public/js/Icinga/module.js)
*/
this.module = module;
this.initialize();
this.module.icinga.logger.info('mymodule module loaded');
};
mymodule.prototype = {
initialize: function()
{
/**
* Tell Icinga about our event handlers, these are then
* automatically detached once Icinga is unloading
*/
this.module.on('rendered', this.showURLs);
},
showURLs: function(event)
{
var pathname = window.location.pathname;
// returns (no matter which site is reloaded): "/icingaweb/module/siteA"
var url = window.location.href;
// returns (no matter which site is reloaded): "http://host/icingaweb/module/siteA#!/icingaweb/module/siteB"
}
};
/**
* Register this module so that Icinga knows about it
*
* It's important that the identifier used is the same
* as the name of the module itself (case sensitive)
*/
Icinga.availableModules.mymodule = mymodule;
}(Icinga));

For those who are interessted in the solution, JoNe an Icinga Web 2 developer answered my question at monitoring-portal.org
You can use the following to get the URL of the currently loaded frame/pages:
$(event.target).closest('.container').data('icingaUrl')
Many thanks to JoNe.

Related

How to deal with a friendly url with parameters in a static webpage?

I have the following URL https://mywebsite/somepage/1234/5678 where somepage is a route to a page and the numbers are are parameters.
My page is a static page, just html and javascript. Ex.: https://mywebsite/somepage.html.
How could I open this page given the above url get the parameters inside the page?
The reason for this is that I have a mobile deeplink direct the user to a website so that it can download the app in case it isn't installed or to the app itself. I don't have the choice to use a dinamic page with a routing system like in Cake PHP or in Spring Framework.
If you want to load the normal page (https://mywebsite/somepage.html) then you could use hashes instead. They don't get seen by the server, so it would serve the regular html file.
// get the url
var url = window.location.href; // = "https://mywebsite/somepage.html#1234/5678"
// get the bit you want
var params = url.substring(32); // = "1234/5678"
// ^ the length of "https://mywebsite/somepage.html#"
// split it apart into individual parts
params = params.split("/"); // = ["1234", "5678"]
// then do whatever you like with the params
Create array from current pathname split on /
var urlPath = window.location.pathname.split('/');
Do something with the array...
urlPath.forEach(function(item) {
console.log(item);
});

How do I make relative file pathing work with include()?

I'm working on a website, and the relevant portion of my file structure is:
site
classes
class1
js
Now, the js contains scripts that use other scripts within the same folder. The only way I can get the scripts to load properly on the php pages is to either copy the whole js folder into the relevant subfolder, or move the page to the site folder. Neither of these options is good.
I know that the issue is with the file pathing, so how do I get the includes in the js scripts to path relative to their location, and not the location of the php page?
An example of this:
I have a page in class1 called class1home.php.
It calls a js script called script.js.
script.js contains a function with include(script2.js), which is in the js folder.
Because of the pathing, the include is looking for site/classes/class1/script2.js.
I want it to go to site/js/script2.js.
Because there are multiple folders and scripts using script2.js, I can't just change the filepath within the include to be relative to that specific page.
Within script.js:
/**
* #function Include
* #description Includes an external scripts to the page
* #param {string} scriptUrl
*/
function include(scriptUrl) {
document.write('<script src="' + scriptUrl + '"></script>');
}
One place it is used (within script.js):
/**
* #module ToTop
* #description Enables ToTop Plugin
*/
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.ui.totop.min.js');
$(document).ready(function () {
$().UItoTop({
easingType: 'easeOutQuart',
containerClass: 'ui-to-top fa fa-angle-up'
});
});
}
})($);
I normally solve this type of problem by having the page identify where it is with a call to Server. It looks like this:
$callingPageURL =$_SERVER['SCRIPT_FILENAME'];
Then, I parse that string to determine the file and the folder, by using the explode function. It looks like this:
$callingPageURLHolder = explode("/", $callingPageURL);
This loads up an array of values into callingPageURLHolder. From there, I use common data structure methods, like array pops, to get to the part of the URL that I think will be relevant to the program. It looks like this:
$callingPageFile = array_pop($callingPageURLHolder);
$callingPageFolder = array_pop($callingPageURLHolder);
Once you can parse out the array that comes back from Server, you could simply load up variables you need to concatenate into a URL that you will call in your include.
This same type of technique can be used to make small changes in a template page based on where it was included from, by adding in some flow control that tests these kinds of extracted values.
For example,
switch ($callingPageFile){
case "index.php":
// some response
break;
}
Using logic like that, I might build chains of cases in which I respond to anticipated URL parts. I use this type of code for when I might want to slightly customize a PHP page. Using these techniques, and some planning, you might be able to respond to the idea that you intend to transplant your code to a variety of places.

Angular replace url after hashbang

In our app, we are serving static angular app files out of foobar.com/public/angular. The home page (foobar.com) is configured to serve foobar.com/public/angular/index.html. Thus, in our index file's <head>, we have:
<base href="http://foobar.com/public/angular">
However, during development, we use foobar.com/debug, which causes the server to use this instead:
<base href="http://foobar.com/public/angular-debug">
The server returns unprocessed (not minified, uglified, etc) versions of the files from this url. We are also using angular-route for our views.
TLDR:
We have a production route: foobar.com
We have a dev route: foobar.com/debug
We have a base tag: <base href="http://foobar.com/public/whatever">
We are using hash-bang urls for angular routes
The trouble is generating urls on the client side. As discussed in comments, Click here does not work because the resulting url contains the base tag, which the server rejects and looks odd since the user starts somewhere else: foobar.com/public/angular/#/myRoute). The best I could think of to create the desired url was this:
/**
* Returns current url after replacing everything after the hashbang with a new string.
*
* #param {string} s - string to change route with (e.g. 'asdf')
* #return {string} - new url e.g. http://google.com/foobar/#!/asdf
*/
makeRouteUrl = function(s) {
var root = $location.absUrl().match(/.*#!/);
if (root && (root.length > 0)) {
root = root[0];
return( root + s );
} else {
// no hashbang in path? Choose home page (not intended use)
return "/";
}
}
However, this just seems a little gross. Is there a function in angular that makes the above function unnecessary? I have looked for functions in $location, $route, etc., but nothing seems to handle our complex setup correctly. We need to ultimately get the url as a string, not navigate (we are supporting open in new tab, so need to used ng-href). Since Angular apps often use hashbang urls for routing, I figured there must be something that allows you the just change the route after the hashbang while still preserving what's in front of it.
I'm not entirely sure if I understand the problem...
$location.url('/stuff/after/hash?params=hey');
Or if you only want to set the path after #:
$location.path('/stuff/after/hash');
Is what I usually use. But you need to return the url without hash after this?
How about
window.location.origin + window.location.pathname
For the current url without hashes and parameters?
Have you considered using the UI Router library?
In general, it's excellent.
Specific to your question, the UrlMatcher service provides a method format that- unless I'm misunderstanding what you're asking- does what you're trying to do.
new UrlMatcher('/your/route/here').format(optionalNamedParameters);
// returns a formatted URL

My relative URL path to my View breaks on Deployment

I have a very standard ASP MVC app that I use a little javascript to show a Partial View. In order to make that Javascript work I needed to hard code a path to the Partial which is different between Dev and Production.
Mainly, in Dev there is no App specification where as in Production there is. See here:
Production=var URL = '/WetWashRequest/wetWashRequests/GetDetails?WONumber=' + wo;
Dev = var URL = '/wetWashRequests/GetDetails?WONumber=' + wo;
What this means is that as I work on it locally I delete the first part and when I want to deploy I have to remember to re add it.
This seems so ridiculously flawed that I can only assume I am being ignorant and doing something wrong...
You can take advantage of UrlHelper to get the URLs, as long as you do it in view:
var URL = '#Url.Action("GetDetails")';
Obviously, it doesn't make sense to put all your JavaScript in view, so what I will normal do is set just this in my view, in a namespace var, and then reference it in my external JavaScript:
View
<script>
var MyApplication = MyApplication || {};
MyApplication.GetDetailsUrl = '#Url.Action("GetDetails")';
</script>
External JS
$.get(MyApplication.GetDetailsUrl, { WONumber: wo }, function (result) {
...
});

Issues in developing web scraper

I want to develop a platform where users can enter a URL and then my website will open the webpage in an iframe. Now the user can modify his website by simply right clicking and I will provide him options like "remove this element", "copy this element". I am almost through. Many of the websites are opening perfectly in iframe but for a few websites some errors have shown up. I could not identify the reason so asking for your help.
I have solved other issues like XSS problem.
Here is the procedure I have followed :-
Used JavaScript and sent the request to my Java server which makes connection to the URL specified by the user and fetches the HTML and then use Jsoup HTML parser to convert relative URLs into absolute URLs and then save the HTML to my disk in Java. And then I render the saved HTML into my iframe.
Is somewhere wrong ?
A few websites are working perfectly but a few are not.
For example:-
When I tried to open http://www.snapdeal.com it gave me the
Uncaught TypeError: Cannot read property 'paddingTop' of undefined
error. I don't understand why this is happening..
Update
I really wonder how this is implemented? # http://www.proxywebsites.in/browse.php?u=Oi8vd3d3LnNuYXBkZWFsLmNvbQ%3D%3D&b=13&f=norefer
2 issues, pick any you like:
your server side proxy code contains bugs
plenty of sites have either explicit frame-break code or at least expect to be top level frame.
You can try one more thing. In your proxy script you are saving your webpage on your disk and then loading into iframe. I think instead of loading the page you saved on disk in iframe try to open that page in browser. All those sites that restirct their page to be loaded into iframe will now get opened without any error.
Try this I think it an work
My Proxy Server side code :-
DateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss");
String dirName = df.format(new Date());
String dirPath = "C:/apache-tomcat-7.0.23/webapps/offlineWeb/" + dirName;
String serverName = "http://localhost:8080/offlineWeb/" + dirName;
boolean directoryCreated = new File(dirPath).mkdir();
if (!directoryCreated)
log.error("Error in creating directory");
String html = Jsoup.connect(url.toString()).get().html();
doc = Jsoup.parse(html, url);
links = doc.select("link");
scripts = doc.select("script");
images = doc.select("img");
for (Element element : links) {
String linkHref = element.attr("abs:href");
if (linkHref != "") {
element.attr("href", linkHref);
}
}
for (Element element : scripts) {
String scriptSrc = element.attr("abs:src");
if (scriptSrc != "") {
element.attr("src", scriptSrc);
}
}
for (Element element : images) {
String imgSrc = element.attr("abs:src");
if (imgSrc != "") {
element.attr("src", imgSrc);
log.info(imgSrc);
}
}
And Now i am just returning the path where i saved my html file
That's it about my server code

Categories

Resources