-
Notifications
You must be signed in to change notification settings - Fork 23
/
jurlp.js
3916 lines (3378 loc) · 91.5 KB
/
jurlp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* File: jurlp.js
*
* Title: JQuery URL parser.
*
* JQuery URL parser plugin for parsing, manipulating, filtering and monitoring URLs in href and src attributes within arbitrary elements (including document.location.href), as well as creating anchor elements from URLs found in HTML/text.
*
* About: Authors
*
* Thomas James Bonner (tom.bonner@gmail.com).
*
* Yonas Sandbæk (seltar@gmail.com).
*
* About: Version
*
* 1.0.4
*
* About: License
*
* Copyright (C) 2012, Thomas James Bonner (tom.bonner@gmail.com).
*
* MIT License:
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**/
/**
*
* Section: URL overview.
*
* URL naming scheme:
*
* A quick quide to URL nomenclature in this plugin.
*
* Throughout this plugin, URLs are segmented and refered to in the following manner;
*
* > http://username:password@www.example.com:443/path/file.name?query=string#anchor
* > |_____||______| |______| |_____________| |_||_____________||___________||_____|
* > | | | | | | | |
* > scheme user password host port path query fragment
* > |______________________________________________________________________________|
* > |
* > url
*
* Scheme:
*
* Contains the protocol identifier (i.e. "https://", "ftp://").
*
* User:
*
* Conains the username to use when connecting to the host server. This segment may be empty.
*
* Password:
*
* Contains the password to use in conjunction with the username when connecting to the remote server. This segment may be empty (and cannot be set without a user name).
*
* Host:
*
* Contains the name or IP address of the host server (i.e. "www.example.com", or "127.0.0.1").
*
* Port:
*
* Contains the listening port number for the host server (i.e. "80", or "8080"). Note that an empty port value implies the default port (80).
*
* Path:
*
* Contains the file path (i.e. "/index.html", or "/").
*
* Query:
*
* Contains any parameters passed in the query (i.e. "?param1=value1¶m2=value2"). This segment may be empty.
*
* Fragment:
*
* Contains any anchors/hash tags (i.e. "#elementname"). This segment may be empty.
*
* Section: URL Objects
*
* URL object definition.
*
* For the purposes of this plugin, URLs can be represented either as a string, for example "http://www.example.com:8080/path/file.name?query=string#anchor", or as an object;
*
* (start code)
*
* {
* scheme: "http://"
* user: "username",
* password: "password",
* host: "www.example.com",
* port: "8080",
* path: "/path/file.name",
* query: "?query=string",
* fragment: "#anchor"
* }
*
* (end code)
*
* Therefore, wherever URLs are supplied as a parameter to the plugin via the <url> or <proxy> methods, either a string or object representation or the URL may be supplied.
*
* URL objects that have been returned via the parser interface can easily be converted to a string by calling the objects toString() method.
*
* Example:
*
* (start code)
*
* // Parse the document.location.href URL, and convert it back to a string again.
* $(document).jurlp("url").toString();
*
* (end code)
*
*/
/**
*
* Section: Quick overview
*
* Useful example code.
*
* (start code)
*
* // Parse and set the element(s) URL
* $("a").jurlp("url");
* $("a").jurlp("url", "http://www.example.com/");
*
* // Get or set individual URL segments for the element(s)
* $("a").jurlp("scheme");
* $("a").jurlp("scheme", "https://");
*
* $("a").jurlp("user");
* $("a").jurlp("user", "username");
*
* $("a").jurlp("password");
* $("a").jurlp("password", "password");
*
* $("a").jurlp("host");
* $("a").jurlp("host", "www.example.com");
*
* $("a").jurlp("port");
* $("a").jurlp("port", "8080");
*
* $("a").jurlp("path");
* $("a").jurlp("path", "../file.name");
*
* $("a").jurlp("query");
* $("a").jurlp("query", {"param":"value"});
*
* $("a").jurlp("fragment");
* $("a").jurlp("fragment", "elementid");
*
* // Filter on URL segments
* $("a").jurlp("filter", "scheme", "^=", "http")
* .jurlp("filter", "user", "=", "user")
* .jurlp("filter", "password", "=", "password")
* .jurlp("filter", "host", "=", "www.example.com")
* .jurlp("filter", "port", "!=", "8080")
* .jurlp("filter", "path", "$=", ".html")
* .jurlp("filter", "query", "*=", "param=value")
* .jurlp("filter", "fragment", "regex", /(\#)/);
*
* // Watch a selector for new nodes
* $("a:eq(0)").jurlp("watch", function(element, selector){})
* .jurlp("filter", "host", "=", "www.example.com")
* .jurlp("query",{"found":"example"});
*
* $("body").prepend("<a href='http://www.example.com/'></a>");
*
* $("a:eq(0)").jurlp("unwatch");
*
* // Parse an element's text for URLs and create/return anchor elements
* $("<div>www.example.com</div>").jurlp();
*
* // Get an interface for parsing/manipulating the supplied URL
* url = $.jurlp("http://www.example.com:80/path/file.name?param1=value1#fragment");
*
* // Parse the URL to an object.
* url.url();
*
* // Get the URL scheme.
* url.scheme();
*
* // Get the URL user name.
* url.user();
*
* // Get the URL password.
* url.password();
*
* // Get the URL host.
* url.host();
*
* // Get the URL port.
* url.port();
*
* // Get the URL path.
* url.path();
*
* // Get the URL query.
* url.query();
*
* // Get a specific parameter value from the URL query.
* url.query().param1;
*
* // Get the URL fragment.
* url.fragment();
*
* // Set the full URL.
* url.url("http://www.example.com:80/path/file.name?param1=value1#fragment");
*
* // Set the URL scheme.
* url.scheme("https://");
*
* // Set the URL user name.
* url.user("user");
*
* // Set the URL password.
* url.password("password");
*
* // Set the URL host.
* url.host("www.newexample.com");
*
* // Set the URL port.
* url.port("80");
*
* // Set the URL path.
* url.path("/newpath/newfile.file");
*
* // Append to the URL path.
* url.path("./newfile.file");
*
* // Remove two path elements and append to the URL path.
* url.path("../../newfile.file");
*
* // Set the URL query.
* url.query("?param=value");
*
* // Append/modify the URL query (string or object)
* url.query("param=value");
* url.query({"param":"value"});
*
* // Remove the URL query
* url.query("");
* url.query({});
*
* // Set the URL fragment.
* url.fragment("#newfragment");
*
* (end code)
*
**/
/**
* Section: Parsing document.location.href
*
* Parsing the document URL.
*
* The document URL (document.location.href) can be parsed by specifying the HTML document element to the parser in the following manner;
*
* (start code)
*
* // Parse the document.location.href URL string into a URL object
* $(document).jurlp("url");
*
* (end code)
*
* Similarly, the document URL can be modified by the plugin, but it is worth noting that changes will not be directly applied to document.location.href until <goto> is explicitly called on the element, and instead, a working copy of the URL is stored under the documents "data-href" attribute.
*
* (start code)
*
* // Does not modify document.location.href (updates $(document).data("href"))
* $(document).jurlp("url", "www.example.com");
*
* // Does modify document.location.href (from $(document).data("href"))
* $(document).jurlp("goto");
*
* (end code)
*
*/
/**
* Section: Parsing elements with an "href" or "src" attribute.
*
* Parsing "href" or "src" attributes.
*
* Elements with an "href" or "src" attribute (i.e. <a href="">, <base href="">, <link href="">, <img src="">, <script src=""> or <iframe src="">), can be parsed by specifying the element(s) to the parser in the following manner;
*
* (start code)
*
* // Parse all anchor element URLs into an array
* $("a").jurlp("url");
*
* (end code)
*
* Any modifications made to the URL will modify the relevant "href" or "src" attribute directly. If you want to visit the URL within an elements "href" or "src" attribute, it is possible to call <goto> on the element.
*
* (start code)
*
* // Directly set the first anchor elements URL, and then goto it!
* $("a:eq(0)").jurlp("url", "www.example.com").jurlp("goto");
*
* (end code)
*
*/
/**
* Section: Parsing element text/HTML.
*
* Parsing text/HTML for URLs.
*
* It is possible for the URL parser to find URLs within text/HTML, and convert them into HTML anchor elements.
*
* (start code)
*
* // Parse the HTML for URLs, and convert all URLs found in the text to anchors.
* $("<div>Here are URLs: www.example1.com, www.example2.com</div>").jurlp();
*
* // HTML becomes:
* <div>
* Here are URLs:
* <a href="http://www.example1.com/" class="jurlp-no-watch">www.example1.com</a>,
* <a href="http://www.example2.com/" class="jurlp-no-watch">www.example2.com</a>
* </div>
* (end code)
*
**/
/**
* Section: Parsing URL strings directly.
*
* How to directly parse, modify or monitor an arbitrary URL string.
*
* (start code)
*
* // Get an interface for parsing the document URL...
* var url = $.jurlp();
*
* // .. or get an interface for parsing your own URL.
* url = $.jurlp("www.example.com");
*
* // Parse the URL to an object.
* url.url();
*
* // Get the URL scheme.
* url.scheme();
*
* // Get the URL host.
* url.host();
*
* // Get the URL port.
* url.port();
*
* // Get the URL path.
* url.path();
*
* // Get the URL query.
* url.query();
*
* // Get a specific parameter value from the URL query.
* url.query().parameter;
*
* // Get the URL fragment.
* url.fragment();
*
* // Create a watch for new URLs that contain "example.com" in the host name
* var watch = $.jurlp("example.com").watch(function(element, selector){
* console.log("Found example.com URL!", element, selector);
* });
*
* // We can even apply filters to the watch to be sure!
* watch.jurlp("filter", "host", "*=", "example.com");
*
* // Append a new URL, which will trigger the watch
* $("body").append("<a href=\"www.example.com\"></a>");
*
* // Stop watching for "example.com" URLs.
* watch.jurlp("unwatch");
*
* (end code)
*
*/
/**
* Section: Unknown URLs.
*
* Overview of unknown URL parsing.
*
* Unknown scheme:
*
* The parser will attempt to parse any type of URL it encounters based on its scheme. However, not all URLs are parsable, for example "spotify:track:<trackid>". In this case, the following URL object is returned;
*
* (start code)
*
* {
* scheme: "spotify:",
* url: "track:<trackid>"
* }
*
* (end code)
*
* The unknown URL object will always contain the scheme (if present), for filtering purposes, and also contains a toString() method, which will convert the URL object back to the original URL string.
*
* mailto:
*
* "mailto:" URLs are parsable in the same manner as a regular HTTP URL. For example, the following URL object is returned for a URL with a "mailto:" scheme;
*
* (start code)
*
* {
* scheme: "mailto:"
* user: "username",
* password: "",
* host: "www.example.com",
* port: "",
* path: "",
* query: "?subject=subject&body=body",
* fragment: ""
* }
*
* (end code)
*
* Therefore, "mailto:" URLs can be fully parsed using this parser, but note that it is not possible to set the password, port or fragment strings on a "mailto:" URL.
*
* javascript:
*
* "javascript" URLs are parsable in the same manner as a regular HTTP URL. For example, the following URL object is returned for a URL with a "javasrcipt:" scheme;
*
* (start code)
*
* {
* scheme: "javascript:"
* user: "",
* password: "",
* host: "www.example.com",
* port: "",
* path: "/",
* query: "",
* fragment: "",
* javascript: "alert('!');"
* }
*
* (end code)
*
* Therefore, "javascript:" URLs can be fully parsed using this parser, but note that the current "document.location.href" will always be parsed/returned as the main URL object.
*
**/
/**
* Section: Operators.
*
* Overview of filter operators.
*
* The following filter operators may be specified as the "operator" parameter to the <filter> method.
*
* URL filter operators:
*
* "=" - Equal to.
* "!=" - Not equal to.
* "*=" - Contains.
* "<" - Less than.
* "<=" - Less than or equal to.
* ">" - Greater than.
* ">=" - Greater than or equal to.
* "^=" - Starts with.
* "$=" - Ends with.
* "regex" - Regular expression.
*
**/
/**
* Section: this parameter.
*
* Where "this" is refered to as an argument to the method functions, it may be one of the following;
*
* - HTML document element.
* - An array of 1 or more elements with a "href" or "src" attribute.
* - A URL parser interface returned from $.jurlp().
*
**/
(
function ( $ )
{
/**
*
* Regular expression for parsing URLs.
*
* Taken from parseUri 1.2 (http://blog.stevenlevithan.com/archives/parseuri).
*
**/
var urlRegEx = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
/*
Global object of watched selectors and their array of callstacks.
*/
var selectorCallStack = { };
/*
Currently watched selector. ToDo: Remove this and use a better mechanism for selector tracking.
*/
var currentSelector = "";
/**
*
* Section: Internal functions.
*
* All internal private functions.
*
* This section contains all internal functions that perform the grunt work for the parser interface.
*
**/
/**
*
* Function: initialiseElement
*
* Initialise an element for use with the URL parser.
*
* Parameters:
*
* this - The element to initialise. See <this parameter>.
*
**/
var initialiseElement = function ( )
{
/* Attempt to retreive a href from the element */
var href = getHref.apply ( this );
/* Was a href found for the element? */
if ( href == "" )
{
/* Is the current element the document? */
if ( this.get ( 0 ) == $( document ).get ( 0 ) )
{
/* Use the document href */
href = document.location.href;
}
else if ( this.is ( "[href]" ) )
{
/* Use the element href attribute */
href = this.attr ( "href" );
}
else if ( this.is ( "[src]" ) )
{
/* Use the element src attribute */
href = this.attr ( "src" );
}
/* Check the href is not empty so we don't initialise the "data-href" attribute on text elements (although maybe this is not wanted, as an empty href is technically the current page?). */
if ( href != "" )
{
/* Sanitise the URL */
href = sanitiseUrl ( href );
/* Store the URL as a data attribute within the element */
this.data ( "href", href );
}
}
};
/**
*
* Function: initialiseElementText
*
* Initialise an elements text field for use with the URL parser.
*
* Parameters:
*
* this - The element to initialise.
*
**/
var initialiseElementText = function ( )
{
/* Is the current element not the document, and also does not contain a "href" attribute */
if ( this.get ( 0 ) != $( document ).get ( 0 ) && this.attr ( "href" ) == null && this.attr ( "src" ) == null )
{
/* Does the element contain anything? */
if ( this.html ( ) != null && this.hasClass ( "jurlp-span" ) == false )
{
var urls = [ ];
var modifiedHtml = false;
var match = "";
/* Regular expression for finding URLs in free text */
var findUrlRegExp = /((((mailto|spotify|skype)\:([a-zA-Z0-9\.\-\:@\?\=\%]*))|((ftp|git|irc|ircs|irc6|pop|rss|ssh|svn|udp|feed|imap|ldap|nntp|rtmp|sftp|snmp|xmpp|http|https|telnet|ventrilo|webcal|view\-source)\:[\/]{2})?(([a-zA-Z0-9\.\-]+)\:([a-zA-Z0-9\.&;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(aero|arpa|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|[a-zA-Z]{2}))(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\?\'\\\+&;%\$\=~_\-]+)?(#\w*)?)*))/i;
/* Store the elements HTML */
var html = this.html ( );
/* Attempt to locate URLs within the HTML */
while ( match = findUrlRegExp.exec ( html ) )
{
/* Replace the URL with a unique ID */
html = html.replace ( match [ 0 ], "$" + urls.length );
/* Store the discovered URL */
urls.push ( match [ 0 ] );
/* Indicate that the HTML was modified */
modifiedHtml = true;
}
/* Iterate through all discovered URLs */
for ( var i = 0; i < urls.length; i++ )
{
/* Get the postion of the current URL ID */
var pos = html.indexOf ( "$" + i );
/* Get the possible attribute name */
var attr = html.substring ( pos - 6, pos - 1 );
/* Does the URL reside within an attribute (i.e. an existing tag) */
if ( attr == "href=" || attr == " src=" || html.substring ( pos - 1, pos ) == ">" )
{
/* Replace the ID with the original URL (do not convert this URL to an anchor as it most likely is part of one) */
html = html.replace ( "$" + i, urls [ i ] );
}
else
{
/* Replace the unique ID with an anchor tag */
html = html.replace ( "$" + i, "<a href=\"[url]\" class=\"jurlp-no-watch\">[url]</a>".replace ( /\[url\]/g, urls [ i ] ) );
}
}
/* Did we change the HTML at all? */
if ( modifiedHtml != false )
{
/* Add a class on the parent element to indicate that we have modified it */
this.addClass ( "jurlp-span" );
/* Update the elements HTML */
this.html ( html );
/* Find and return all newly created anchor tags */
return this.find ( "a[href]" ).each
(
function ( )
{
/* Get the href attribute for the element */
var href = getHref.apply ( $( this ) );
/* Sanitise the URL and reset the elements href */
setHref.apply ( $( this ), [ href ] );
}
);
}
}
}
/* No URLs found */
return null;
}
/**
*
* Function: setAttrUrl
*
* Given an element, and an attribute, set the attribute to the supplied URL, and created a backup of the original URL if not already done.
*
* Note, if the attribute doesn't exist, then it will not be created.
*
* Parameters:
*
* this - The element to set the attribute URL on.
*
* attr - The name of the attribute to set.
*
* url - The value of the attributes URL.
*
**/
var setAttrUrl = function ( attr, url )
{
/* Is the attribute present on this element? */
if ( this.is ( "[" + attr + "]" ) != false )
{
/* Has a copy of the original attribute been stored? */
if ( this.data ( "original-" + attr ) == null )
{
/* Store a copy of the original attribute */
this.data ( "original-" + attr, this.attr ( attr ) );
}
/* Update the elements attribute */
this.attr ( attr, url );
}
};
/**
*
* Function: restoreAttrUrl
*
* Given an element, and an attribute, then restore the URL attribute value to its original value.
*
* Parameters:
*
* this - The element to restore the attribute URL on.
*
* attr - The name of the attribute to restore.
*
**/
var restoreAttrUrl = function ( attr )
{
/* Was a backup of the original attribute URL made? */
if ( this.data ( "original-" + attr ) != null )
{
/* Restore the attribute URL */
this.attr ( attr, this.data ( "original-" + attr ) );
/* Remove the original URL */
this.removeData ( "original-" + attr );
}
};
/**
*
* Function: restoreElement
*
* Destroys any data associated with an element that has previously been initialised for use with the URL parser, and restores the elements "href" or "src" attribute (if any) to its original value.
*
* Parameters:
*
* this - The element to destroy.
*
**/
var restoreElement = function ( )
{
/* Remove the working href URL */
this.removeData ( "href" );
/* Restore the href attribute */
restoreAttrUrl.apply ( this, [ "href" ] );
/* Restore the src attribute */
restoreAttrUrl.apply ( this, [ "src" ] );
/* Remove any watch attributes */
this.removeData ( "jurlp-no-watch" );
this.removeData ( "is-watched" );
/* clean up selector callstack and unbind */
methods.unwatch.apply ( this );
}
/**
*
* Function: getHref
*
* Get the href URL for the element. Prioritises internal objects href, over "data-href", over "href", over "src" attributes.
*
* Parameters:
*
* this - The element to retieve the URL value from.
*
**/
var getHref = function ( )
{
return this.href || this.data ( "href" ) || this.attr ( "href" ) || this.attr ( "src" ) || "";
};
/**
*
* Function: updateHref
*
* Update a segment of the elements href URL.
*
* Parameters:
*
* this - The element to update the URL value on.
*
* segment - The segment to update ("scheme", "host", "port", "path", "query" or "fragment").
*
* value - The new value for the segment.
*
**/
var updateHref = function ( segment, value )
{
setHref.apply ( this, [ setUrlSegment ( getHref.apply ( this ), segment, value ) ] );
};
/**
*
* Function: updateHrefShim
*
* Shim function for reorganising parameters before calling updateHref(). Called via the each callback.
*
* Parameters:
*
* this - The element to update the URL value on.
*
* parameters - Array containing segment and value parameters for updateHref().
*
**/
var updateHrefShim = function ( parameters )
{
updateHref.apply ( this, [ parameters [ 0 ], parameters [ 1 ] ] );
};
/**
*
* Function: setHref
*
* Sets the href URL value for an element.
*
* Parameters:
*
* this - The element to set the URL value on.
*
* url - The new url (string) value.
*
**/
var setHref = function ( url )
{
/* Ensure the supplied URL is a string */
if ( typeof url == "object" )
{
url = objectToUrl ( url );
}
/* Sanitise the URL - slow and horrible :( */
url = sanitiseUrl ( url );
if ( this.href != null )
{
this.href = url;
return;
}
/* Is the current element the document? */
if ( this.get ( 0 ) == $( document ).get ( 0 ) )
{
/* Current element is the document. Save the href under a data attribute. */
this.data ( "href", url );
}
else
{
/* Update href URL (if present) */
setAttrUrl.apply ( this, [ "href", url ] );
/* Update src URL (if present) */
setAttrUrl.apply ( this, [ "src", url ] );
}
};
/**
*
* Function: urlToObject
*
* Parse a URL into segments using the DOM. Parses authority information from the URL using parseUri (http://blog.stevenlevithan.com/archives/parseuri).
*
* Parameters:
*
* url - URL String to parse.
*
* Returns:
*
* URL object.
*
**/
var urlToObject = function ( url )
{
/* Was a null URL supplied? */
if ( url == null )
{
/* Return an empty object */
return { scheme : "", user : "", password : "", host : "", port : "", path : "", query : "", fragment : "" };
}
var credentials = { user : "", password : "" };
if ( url.substring ( 0, 2 ) == "//" )
{
url = "http:" + url;
}
/* If a URL is supplied, ensure a protocol is specified, otherwise the parser will assume that the supplied host is the path */
if ( url != "" && url.indexOf ( "://" ) == -1 )
{
url = "http://" + url;
}
/* Does the URL contain authority information? */
if ( url.indexOf ( "@" ) != -1 )
{
/* Parse the URL using regex */
var urlSegments = url.match ( urlRegEx );
/* Was a username found? */
if ( urlSegments [ 4 ] )
{
credentials.user = urlSegments [ 4 ];
}
/* Was a password found? */
if ( urlSegments [ 5 ] )
{
credentials.password = urlSegments [ 5 ];
}
}
/* Construct a new anchor element based on the supplied URL */
var a = document.createElement ( "a" );
/* Set the anchor href to the URL to parse (let the browser do (most of) the parsing) */
a.href = url;
/* Under IE, an anchor element containing a username and password is inaccessible, so we will probe "a.protocol" to test if we have access */
try
{
/* Check if the element is accessible */
var accessible = a.protocol;
}
catch ( err )
{
/* MSIE: A security problem occurred. (cannot access the anchor element) */
if ( err.number == -2146697202 )
{
/* IE hack!.. strip the username and password from the URL, and reparse */
var authority = "";