Fully deprecate function-style constructor for Keycloak JS (#19438)

This commit is contained in:
Jon Koops 2023-04-03 14:45:55 +02:00 committed by GitHub
parent 85c0b47c31
commit bdc019b02c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 30 additions and 4 deletions

View file

@ -49,3 +49,19 @@ try {
alert('failed to initialize');
}
```
= Keycloak JS adapter must be instanciated with the `new` operator
Historically it has been possible to create an instance of the Keycloak JS adapter by calling the `Keycloak()` function directly:
```js
const keycloak = Keycloak();
```
To align this with modern conventions in the JavaScript world it has been possible to use the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new[`new` operator] to create an instance instead:
```js
const keycloak = new Keycloak();
```
The function-style constructor has been deprecated for a while, but starting this version we will actively log a deprecation message when it used. This style of constructor will be removed in a future version so make sure to migrate your code to use the `new` operator.

View file

@ -130,7 +130,7 @@
document.getElementById('events').innerHTML = new Date().toLocaleString() + "\t" + event + "\n" + e;
}
var keycloak = Keycloak();
var keycloak = new Keycloak();
keycloak.onAuthSuccess = function () {
event('Auth Success');

View file

@ -21,8 +21,18 @@ if (typeof Promise === 'undefined') {
throw Error('Keycloak requires an environment that supports Promises. Make sure that you include the appropriate polyfill.');
}
var loggedConstructorDeprecation = false;
function logConstructorDeprecation() {
if (!loggedConstructorDeprecation) {
loggedConstructorDeprecation = true;
console.warn('[KEYCLOAK] Instantiation using the `Keycloak` function has been deprecated and support will be removed in future versions. Use the `new` operator to create an instance instead.');
}
}
function Keycloak (config) {
if (!(this instanceof Keycloak)) {
logConstructorDeprecation();
return new Keycloak(config);
}

View file

@ -167,10 +167,10 @@ public class JavascriptTestExecutor {
jsExecutor.executeScript("console.warn = event;");
if (argumentsBuilder == null) {
jsExecutor.executeScript("window.keycloak = Keycloak();");
jsExecutor.executeScript("window.keycloak = new Keycloak();");
} else {
String configArguments = argumentsBuilder.build();
jsExecutor.executeScript("window.keycloak = Keycloak(" + configArguments + ");");
jsExecutor.executeScript("window.keycloak = new Keycloak(" + configArguments + ");");
}
jsExecutor.executeScript("window.keycloak.onAuthSuccess = function () {event('Auth Success')};"); // event function is declared in index.html

View file

@ -124,7 +124,7 @@
<body>
<script>
var keycloak = Keycloak({
var keycloak = new Keycloak({
authServerUrl: authUrl,
realm: realm,
clientId: 'account-console'