Skip to content

Commit

Permalink
Merge pull request #685 from Mas0nShi/678-fixes-window-location-href
Browse files Browse the repository at this point in the history
#678@patch: Assign of window.location.href.
  • Loading branch information
capricorn86 committed Apr 12, 2023
2 parents 121fc96 + ca325ca commit fdbfc53
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
33 changes: 32 additions & 1 deletion packages/happy-dom/src/location/Location.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { URL } from 'url';
import DOMException from '../exception/DOMException';
import DOMExceptionNameEnum from '../exception/DOMExceptionNameEnum';

/**
*
Expand All @@ -11,6 +13,35 @@ export default class Location extends URL {
super('about:blank');
}

/**
* Override set href.
*/
// @ts-ignore
public set href(value: string) {
try {
super.href = this.hostname ? new URL(value, this).href : value;
} catch (e) {
if (this.hostname) {
throw new DOMException(
`Failed to construct URL from string "${value}".`,
DOMExceptionNameEnum.uriMismatchError
);
} else {
throw new DOMException(
`Failed to construct URL from string "${value}" relative to URL "${super.href}".`,
DOMExceptionNameEnum.uriMismatchError
);
}
}
}

/**
* Override set href.
*/
public get href(): string {
return super.href;
}

/**
* Replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
*
Expand All @@ -29,7 +60,7 @@ export default class Location extends URL {
* @see this.replace()
*/
public assign(url: string): void {
this.replace(url);
this.href = url;
}

/**
Expand Down
28 changes: 28 additions & 0 deletions packages/happy-dom/test/location/Location.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import DOMException from '../../src/exception/DOMException';
import DOMExceptionNameEnum from '../../src/exception/DOMExceptionNameEnum';
import Location from '../../src/location/Location';

const HREF = 'https://google.com/some-path/?key=value&key2=value2#hash';
Expand Down Expand Up @@ -30,4 +32,30 @@ describe('Location', () => {
expect(location.href).toBe(HREF);
});
});

describe('href', () => {
it('Successully sets a relative URL.', () => {
location.href = HREF;
expect(location.href).toBe(HREF);
location.href = '/foo';
expect(location.href).toBe('https://google.com/foo');
});

it('Fails when it is not possible to construct a relative URL.', () => {
let error: Error | null = null;

try {
location.href = '/foo';
} catch (e) {
error = e;
}

expect(error).toEqual(
new DOMException(
`Failed to construct URL from string "/foo" relative to URL "about:blank".`,
DOMExceptionNameEnum.uriMismatchError
)
);
});
});
});

0 comments on commit fdbfc53

Please sign in to comment.