Skip to content

Commit 213d7ba

Browse files
committed
Add Python and JS tests for redirecting from component method.
1 parent c16d550 commit 213d7ba

File tree

10 files changed

+354
-7
lines changed

10 files changed

+354
-7
lines changed

django_unicorn/static/js/component.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export class Component {
2828

2929
this.document = args.document || document;
3030
this.walker = args.walker || walk;
31+
this.window = args.window || window;
3132

3233
this.root = undefined;
3334
this.modelEls = [];

django_unicorn/static/js/messageSender.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export function send(component, callback) {
3131
Accept: "application/json",
3232
"X-Requested-With": "XMLHttpRequest",
3333
};
34-
headers[component.csrfTokenHeaderName] = getCsrfToken();
34+
headers[component.csrfTokenHeaderName] = getCsrfToken(component);
3535

3636
fetch(component.syncUrl, {
3737
method: "POST",
@@ -58,8 +58,13 @@ export function send(component, callback) {
5858
}
5959

6060
// Redirect to the specified url if it is set
61-
if (responseJson.redirect) {
62-
window.location = responseJson.redirect.url;
61+
// TODO: For turbolinks support look at https://github.com/livewire/livewire/blob/f2ba1977d73429911f81b3f6363ee8f8fea5abff/js/component/index.js#L330-L336
62+
if (responseJson.redirect && responseJson.redirect.url) {
63+
component.window.location.href = responseJson.redirect.url;
64+
65+
if (isFunction(callback)) {
66+
callback([], null, null);
67+
}
6368
}
6469

6570
// Remove any unicorn validation messages before trying to merge with morphdom

django_unicorn/static/js/utils.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,10 @@ export function $(selector, scope) {
6060
/**
6161
* Get the CSRF token used by Django.
6262
*/
63-
export function getCsrfToken() {
63+
export function getCsrfToken(component) {
6464
// Default to looking for the CSRF in the cookie
6565
const cookieKey = "csrftoken=";
66-
const csrfTokenCookie = document.cookie
66+
const csrfTokenCookie = component.document.cookie
6767
.split(";")
6868
.filter((item) => item.trim().startsWith(cookieKey));
6969

@@ -72,7 +72,9 @@ export function getCsrfToken() {
7272
}
7373

7474
// Fall back to check for the CSRF hidden input
75-
const csrfElements = document.getElementsByName("csrfmiddlewaretoken");
75+
const csrfElements = component.document.getElementsByName(
76+
"csrfmiddlewaretoken"
77+
);
7678

7779
if (csrfElements && csrfElements.length > 0) {
7880
return csrfElements[0].getAttribute("value");

0 commit comments

Comments
 (0)