Skip to content

Commit aa6e055

Browse files
committed
issue/910: Fix CORS warning for localhost
See maplibre#910 Don't show CORS warning for localhost
1 parent 0f1000c commit aa6e055

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/components/InputUrl.tsx

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,22 @@ function validate(url: string, t: TFunction): JSX.Element | undefined {
1010
}
1111

1212
let error;
13-
const getProtocol = (url: string) => {
13+
const getUrlParams = (url: string) => {
14+
let protocol: string | undefined;
15+
let isLocal = false;
16+
1417
try {
1518
const urlObj = new URL(url);
16-
return urlObj.protocol;
17-
}
18-
catch (err) {
19-
return undefined;
19+
20+
protocol = urlObj.protocol;
21+
// Basic check against localhost; 127.0.0.1/8 and IPv6 localhost [::1]
22+
isLocal = /^(localhost|\[::1\]|127(.[0-9]{1,3}){3})/i.test(urlObj.hostname);
23+
} catch (err) {
2024
}
25+
26+
return { protocol, isLocal };
2127
};
22-
const protocol = getProtocol(url);
28+
const {protocol, isLocal} = getUrlParams(url);
2329
const isSsl = window.location.protocol === "https:";
2430

2531
if (!protocol) {
@@ -40,7 +46,8 @@ function validate(url: string, t: TFunction): JSX.Element | undefined {
4046
else if (
4147
protocol &&
4248
protocol === "http:" &&
43-
window.location.protocol === "https:"
49+
window.location.protocol === "https:" &&
50+
!isLocal
4451
) {
4552
error = (
4653
<SmallError>
@@ -76,10 +83,10 @@ type FieldUrlState = {
7683

7784
class FieldUrlInternal extends React.Component<FieldUrlInternalProps, FieldUrlState> {
7885
static defaultProps = {
79-
onInput: () => {},
86+
onInput: () => { },
8087
}
8188

82-
constructor (props: FieldUrlInternalProps) {
89+
constructor(props: FieldUrlInternalProps) {
8390
super(props);
8491
this.state = {
8592
error: validate(props.value, props.t),
@@ -100,7 +107,7 @@ class FieldUrlInternal extends React.Component<FieldUrlInternalProps, FieldUrlSt
100107
this.props.onChange(url);
101108
}
102109

103-
render () {
110+
render() {
104111
return (
105112
<div>
106113
<InputString

0 commit comments

Comments
 (0)