Create empty URL object from scratch in JavaScript - javascript

I want to manually construct URL from parts using the URL object.
However, it's constructor requires a proper URL string to be passed to it, which doesn't allow to start from empty object and build it progressively.
Is there a way to overcome this limitation somehow?
What caused such design decision in the first place?

You have already figured out the workaround and there is no alternative other than passing the parts in or starting with a URL and mutating it.
I'll try to answer:
What caused such design decision in the first place?
By far the most common use case for URLs was to create a URL from a URL string. Someone actually did end up asking for the API you are describing in the URL spec and discussion mostly stalled.
We have an API in Node.js for constructing URLs from parts - but that creates a string one would still need to pass to the URL constructor.
So this is likely not a bad idea and it is currently blocked on someone actually doing the work of adding that capability.

The only workaround I've found so far is to use minimal correct URL to initialize the object and then to override it's parts (namely protocol and host).
const url = new URL('https://example.com');
url.protocol = 'http';
url.host = 'google.com';
console.log(url.toString()); // outputs: http://google.com/
However, it's still cumbersome for this use case.

Related

Hook window.location.* assignments and window.location.assign

I'm trying to intercept window.location.* assignments and window.location.assign calls to change the url assigned before leaving is that possible?
when I try to redefine the property setter I get an error that I can't redefine it.
Is my only option is to proxy the page and statically replace all assignments to window.location with string replace?
Although I rather avoid it since javascript is funky and something like this could also be valid so I would have to keep track of all assignments:
var l = window.location;
var c = l;
var t = c.assign;
t('...');
One solution would to be to create your own location change provider where you could intercept the URL and make changes accordingly. Your code could then always call your change provider rather than the standard window.location property.
Of coarse this would not work if you are in a situation where the code that is setting the location property is out of your control.
If the location setting code is out of your control, take a look at Javascript: How to intercept window.location change where the beforeunload event is used.
Unfortunately, I don't think you can do this. As you've found, the location property on window is non-configurable (at least in Chrome and Firefox). And as you know, it's very special: If you attempt to write to it (e.g., to replace it with your own customized object), instead of replacing the property in the normal way, it will convert what you give it to a string and attempt to navigate there. Consequently, there's no way for you to replace window.location with your own thing: Object.defineProperty won't let you (because it's non-configurable), and assignment won't work.
That leaves you with the task of identifying all writes to window.location in the JavaScript code on the page, which is impossible in the general case. While you could find all window.location and location references, and static analysis would tell you (absent eval or new Function) whether those window and location variables are the globals, you would need to evaluate the code step-by-step to find the kind of thing you mentioned in your question, or even something simple like:
(function(w) {
w.location = "https://stackoverflow.com";
})(this);
Completely changing the architecture of your solution, you could run a headless browser server-side and echo changes to its DOM to the client, intercepting all clicks and forwarding them to server-side code to pass to the headless browser. Which likely has its own significant challenges.

What does 'x' mean as the last letter in `src` attribute

In some projects I noticed that javascripts included into HTML like this:
<script type="text/javascript" src="./js/score.js?x"></script>
What's mean last 'x' symbol?
It is a query string which may be used to pass variables to the script.
It will help to overcome cache problems as well.
If I had to guess, I would say the X is being used as a querystring fragment. Unless the server is depending on the fragment being there, it could possibly be used as a cache buster.
Essentially, by changing that X to a Y we could make the browser fetch a fresh copy. This is useful if you need to make sure users get a new copy of a file.
Of course, without talking to the author we are just guessing. Perhaps the server needs it there to properly build the file in the first place. Or maybe the javascript itself is using it.
It is not a symbol. It is a piece of query string like on web scripts it would be something like test.php?reload=true
Such techniques might be helpful to overcome the caching problem as mentioned by SLaks on the comments.
You can pass parameters to your javascript.
It can be used to initiliaze variable or be used somewhere.
Take a look at this link http://feather.elektrum.org/book/src.html

Using a full URL with Restangular

I like all of the functions of Restangular for AngularJS, except that I can't find (and it may not support) a way of just passing a full URL to it. I realize the benefit of the .one('something','someparam') but my issue is that I'm passed various URL strings, and I really don't want to have to split() them just to use Restangular.
Also, I know about the baseURL function; but these URLs I'm being passed don't necessarily derive from the same base path.
For example, I might have:
/us/en/product/17726
/us/es/products
/us/es/product/991A0
/ca/en/accounts
All I'm given are the Strings...
I'm the creator of Restangular.
You have 2 options to do that.
1) Creating scoped Restangulars with different BaseURLs in each case: https://github.com/mgonto/restangular#how-to-create-a-restangular-service-with-a-different-configuration-from-the-global-one
2) You can use it like Restangular.all('us/en/').one('products', 1726) or Restangular.one('us/en/product', 1234)
Hope it works for you :)
I needed to simply GET an absolute url and came across this question.
Here's how:
Restangular.oneUrl('routeName', 'http://absolute.url').get();
restangular#restangular-methods

How to create a submatch for this expression?

I am running a regular expression against the DOM to return back an account status from a page.
This is the string on the page:
<h3>Status</h3><p>Completed</p>
And this is the Expression I'm currently using
<h3>Status</h3>[\s\S]*?<p>([\s\S]*?)</p>
My goal is to only get the Status of "Completed" from this string but not sure on how to do this. I have read a little on submatching; just not sure how to implement it.
re.match() returns an array containing the sub-matches for each capture group. So use:
var re = new RegExp('<h3>Status</h3>[\s\S]*?<p>([\s\S]*?)</p>');
var match = re.match(str);
var submatch = match[1];
This will work: /<h3>Status<\/h3>[\s\S]*<[^>]*>([^<]+)<.*/
See it working here: http://jsfiddle.net/M7kJ7/
But seriously... use DOM functions for that! Why a regex?
EDIT: Example of how you could solve it using DOM functions: http://jsfiddle.net/DycGh/
EDIT2: OK, after reading all the comments, I came to the conclusion that you do have valid reason to not access directly the database (you can't! they don't give you access to it)
And you can't use native DOM functions (you are not executing js directly on each page, but instead one central page is going to be used for searching the other pages)
,
However, I still don't think browser-side javascript is the correct path.
Using either server-side javascript (node.js), or some other language, like perl would be better. And using DOM, by means of a parser, is correct too.
If you choose with the node.js path, you can use node-htmlparser. From your node app you'll open each url, get the data using the parser's functions and then construct a json output. Your page will make an ajax request to node, and get its json results, which you will use to create the output.
If you go for perl, you can use HTML::DOM. The rest of the procedure would be similar.
It doesn't has to be perl or node.js, is just the options I know. With php, python or ruby you can do it too. (but you'll have to google for parsers)
But is best if you do it with a server-side script.

Javascript url management

I need help because I am trying to create a lib with javascript in order to create, modify, delete params in my url, I explain :
www.mydomain.com/thing/?id=1&et=67&type=chercher
How u can see, my params are random, it's dynamic, It's not every time the same url, I had this url, one time I can have ?id=1&et=67&type=chercher and other time I can have ?id=1&type=chercher or for example just ?id=1 or others params.
So it's not easy because of user action, the url with params will change, so is there an lib or an application written with javascript which can do this easily ?
Thx everyOne for your futures responses !!!!
You are creating a library to manipulate URLs? Have you had a look at the existing solutions?
URI.js is something I can recommend. In its Readme URI.js links to a bunch of alternative solutions you could look into as well.
Yes, absolutely. You can use the jQuery URL Parser plugin. Just make sure you include also jQuery in your page and not only the plugin.
Do u need library which manipulate URL string?
pass associative array(HASH) to function {a:2, b:3, c:4} and then go through this hash and form string.
Is this what u need?
To update - split string by & and downparse into HASH, and replace value by H['a'] = 4;
To delete - delete H["a"];
But better do not reinvent bicycle use tested solutions: http://code.google.com/p/jsuri/

Categories

Resources