I am trying to send data from the main process to the renderer and the ipcRenderer.on function is being executed but the data is undefined...
This is the code to send the data:
mainWindow.webContents.on("did-finish-load", () => {
let name = "test";
mainWindow.webContents.send("updateSave", name);
})
And this to receive it:
ipcRenderer.on("updateSave", (e, data) => {
console.log("data: " + data);
})
The console.log is beeing fired but it just says: data: undefined
And this is the preload file:
contextBridge.exposeInMainWorld("ipcRenderer", {
send: (channel, ...args) => ipcRenderer.send(channel, ...args),
on: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(...args))
});
Does anybody know what I did wrong? Thanks
In your preload.js, you're defining ipcRenderer.on() as follows:
on: (channel, func) => {
ipcRenderer.on(
channel,
(event, ...args) => {
func(...args)
}
)
}
Thus, event will never get passed to func() and is thus swallowed. Now, there are two possible solutions (personally, I'd go with (1) because it's easiest to implement and will make for cleaner code on both parts. However, please see the remark below):
(1) You want to keep the signature in your renderer
I.e., you want to still write ipcRenderer.on("channel", (event, data) => {});. Then you will have to change your preload code. I suggest to simply pass func to ipcRenderer like so:
on: (channel, func) => ipcRenderer.on (channel, func)
Then, any func parameter must have the signature (event, ...data) => {}.
(2) You want to keep the signature in your preload
I.e., you want to keep the code of your preload contextBridge definition. Then, any instance of ipcRenderer.on() in your renderer code will need to change to fit the signature (...data) => {} since there's no event parameter passed to the function.
As a side note, it is considered a best practice if you don't expose Electron API function (such as ipcRenderer.on(), ipcRenderer.send() etc) to the renderer when proxying using a preload script, but instead provide discrete functions for your renderer code to choose from, as shown in Electron's official IPC tutorial.
Related
I'm using Formik to create a form for a React web app. The submission is as the following code.
const submitForm = (values) => {
console.log(JSON.stringify(values, null, 2));
setFormStatus(status.loading);
// handle request.
axios
.put("#", values)
.then(() => {
console.log("Submission Success");
setFormStatus(status.success);
})
.catch(() => {
console.log(`Submission Failure`);
setFormStatus(status.failure);
})
.then(() => {
console.log("Submission CleanUp");
setTimeout(() => {
console.log("Neutralizing Form");
setFormStatus(status.neutral);
// tell to animate.
setSwitchSubmitBtn(!switchSubmitBtn);
}, 2000);
});
};
After the axis request, there will be a 2s delay before I set the status state back to neutral.
However, I'm testing using Jest, waitFor doesn't work as expected. The timeout in submission seems blocked, as no matter how long I wait for the submission, it just won't occur. I found a solution to this by using jest.advanceTimer, but adding the same amount of delay in waitFor doesn't work.
it("INPUT_FORM_TC_008", async () => {
jest.useFakeTimers();
render(<InputForm />);
axios.put.mockImplementation(async () => {
console.log("MOCKED PUT");
return Promise.reject();
});
// click submit Button
user.click(screen.getByTestId("submitBtn"));
await waitFor(() => {
expect(screen.queryByTestId("crossIcon")).not.toBeNull();
});
act(() => {
jest.advanceTimersByTime(2000);
});
await waitFor(() => {
// crossIcon will be unmounted once `status` changes to neutral.
expect(screen.queryByTestId("crossIcon")).toBeNull();
});
});
The following code won't work if I don't use jest.advanceTimer, even I set timeout much longer than the one in submission.
await waitFor(() => {
expect(screen.queryByTestId("crossIcon")).toBeNull();
}, 5000);
I suspect that this is related to the event loop stuff, but I tried to set the timeout to be 20ms in the submission and it works. So I looking for a reason why this happens.
I tried to test a state change using setTimeOut using Jest. I expect after the amount of time I specified in setTimeOut the state should be changed. But using waitFor won't work even set a longer timeout.
The issue is that you are setting a setTimeout in a scope that is immediately exited. This code should still work when it's actually run due to a closure on your function, but in Jest the test will say, "welp, looks like there's no more synchronous code" and finish the test before waiting for the execution.
If you want more information on why setTimeout behaves this way you can check the MDN article here: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
But putting it very simply, it uses something called the "event loop" which is how JS handles asynchronous code while still being a synchronous language. When you use setTimeout, you're simply adding the function execution to the event loop and saying, "Don't execute this code now, run other code until the 2000 ms have gone by, then run this code." Which works fine in your implementation because you're allowing 2000ms to go by. But Jest doesn't wait, it just says "There's no more code to execute and nothing is ready in the event loop, the test must be complete" and cleaning everything up immediately.
You could resolve this by wrapping your setTimeout in a promise, like:
//........
.then(() => {
console.log("Submission CleanUp");
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Neutralizing Form");
resolve(status.neutral);
}, 2000);
})
});
Then have your actual implementation code wait for the promise to resolve and set your formStatus and submissionButton states after the Promise is resolved. This would be a simpler API, would allow for greater abstraction, and would make testing easier since you'd now be able to wait for this execution to finish with a .then() block in your tests as well.
Using this plugin as a reference, I have Flex configured to be able to send a call to a Twilio Studio IVR, after an agent has accepted a call.
I'd like to be able to send an incoming call back to Studio when an agent rejects a call (i.e. as soon as they click the reject button). I'm trying to do this by adding a listener to the plugin's init method:
flex.Actions.addListener("afterRejectTask", async (payload, abortFunction) => {
let url: string = payload.task.attributes.transferToIvrUrl;
let menu: string = 'hangup';
await request(url, { CallSid: payload.sid, menu });
});
See here for the full context -- I'm pretty much using that exact code, with the addition of this listener.
I'm getting this error message, and the call is not transferred anywhere.
twilio-flex.unbundled-react.min.js:1574 Error on afterRejectTask: SyntaxError: Unexpected token < in JSON at position 0
Here's additional context from the console, if that's helpful:
Additional info:
The url being requested is a Twilio function, which successfully returns a response like this:
<Response>
<Enqueue workflowSid="WWcc1a650e4175089538d754a6c2e15a98">
<Task>{"transferToIvrUrl": "https://my-twilio-function-service.twil.io/studio-flex-transfer-helper"}</Task>
</Enqueue>
</Response>
Any advice would be appreciated.
Ah, ok, so looking at that plugin I found the example Twilio Function that works with it. From what I can tell, this function is intended to be used in two places, either in Studio to transfer the call to Flex (though I'm not sure it's needed for that) or from Flex to transfer the call back to Studio. The thing that triggers the different response is whether you pass an argument called transferToIVRMenu with the request.
Your current request is not passing that argument, you currently have:
await request(url, { CallSid: payload.sid, menu });
which looks similar to the original plugin's request:
await request(transferToIvrUrl, { CallSid: call_sid, transferToIVRMenu });
The difference is in the second property in the object. When you just pass the name of the variable in an object, it expands to call the property the same name as the variable and set the value to the value within the variable. So the original request expands out to:
await request(transferToIvrUrl, { CallSid: call_sid, transferToIVRMenu: transferToIVRMenu });
but your request only expands to:
await request(url, { CallSid: payload.sid, menu: menu });
So you are passing a parameter called menu not transferToIVRMenu and that triggers the Function on the back end to return TwiML and not to update the call.
To fix this, you can update your plugin code to send the transferToIVRMenu parameter, like:
flex.Actions.addListener("afterRejectTask", async (payload, abortFunction) => {
let url: string = payload.task.attributes.transferToIvrUrl;
let menu: string = 'hangup';
await request(url, { CallSid: payload.sid, transferToIVRMenu: menu });
});
In my App I have two windows: mainWindow and actionWindow. On my mainWindow I use the ipcRenderer.on listener to receive as message from the main process when the actionWindow is closed. The message however doesn't come through.
The mainWindow is used to control actions that take place on the actionWindow (e.g. navigate to an URL, remotely close the window, ...). I want to give the user the power to move and close the actionWindow manually as well, which is why its title bar is visible and usable.
I expose ipcRenderer.invoke for two-way communication and ipcRenderer.on to the mainWindow's renderer via contextBridge in a preload file.
This is what the code looks like (based on vite-electron-builder template)
main process
const mainWindow = new BrowserWindow({
show: false, // Use 'ready-to-show' event to show window
webPreferences: {
nativeWindowOpen: true,
webviewTag: false,
preload: join(__dirname, "../../preload/dist/index.cjs"),
},
});
const actionWindow = new BrowserWindow({
// some props
})
actionWindow.on("close", () => {
console.log("window closed")
mainWindow.webContents.send("closed", { message: "window closed" });
});
preload
contextBridge.exposeInMainWorld("ipcRenderer", {
invoke: ipcRenderer.invoke,
on: ipcRenderer.on,
});
renderer (mainWindow)
window.ipcRenderer.on("closed", () => {
console.log("message received")
// do something
});
I know for a fact that
mainWindow has access to the exposed listeners, since invoke works and the actions it fires on the main process are executed on the actionWindow as supposed + the response also comes back to the renderer.
the close listener on the actionWindow works since I can see the log window closed in my console
message received doesn't appear in my dev tools console
To me this means that either
mainWindow.webContents.send doesn't work -> the message is never sent
window.ipcRenderer.on doesn't work -> the message never reaches its destination
So either my code is buggy or Electron has recently put some restrictions on one of these methods which I'm not aware of.
Any ideas?
If there is a smarter way to do this than IPC I'm also open to that.
Ok after hours of searching, trying and suffering I (almost accidentaly) found a solution to my problem. It really seems to be the case that electron simply doesn't do anything anymore when you call the on method from your renderer.
Studying the docs about contextBridge again I saw that the way I exposed invoke and on to the renderer, was considered bad code. The safer way to do this is expose a function for EVERY ipc channel you want to use. In my case using TypeScript it looks like this:
preload
contextBridge.exposeInMainWorld("ipcRenderer", {
invokeOpen: async (optionsString: string) => {
await ipcRenderer.invoke("open", optionsString);
},
onClose: (callback: () => void) => {
ipcRenderer.on("closed", callback);
},
removeOnClose: (callback: () => void) => {
ipcRenderer.removeListener("closed", callback);
},
});
renderer(mainWindow)
window.ipcRenderer.onClose(() => {
// do sth
});
window.ipcRenderer.invokeOpen(JSON.stringify(someData)).then(() => {
// do sth when response came back
});
NOTE: To prevent memory leaks by creating listeners on every render of the mainWindow you also have to use a cleanup function which is provided with removeOnClose (see preload). How to use this function differs depending on the frontend framework. Using React it looks like this:
const doSth= () => {
console.log("doing something")
...
};
useEffect(() => {
window.ipcRenderer.onClose(doSth);
return () => {
window.ipcRenderer.removeOnClose(doSth);
};
}, []);
Not only is this a safer solution, it actually suddenly works :O
Using the cleanup function we also take care of leaks.
I'm able to send get and put methods fine, but am surprisingly not able to send a delete fetch request from my Redux action to my Rails backend. This is even more perplexing because in Postman I'm able to hit the Destroy route fine. I've searched all over for a fix, but haven't found anything that works. I have an onClick function that triggers the Redux action that sends this request:
export const deleteQuestion = (questionId, routerHistory) => {
return dispatch => {
return fetch(`${API_URL}/questions/${questionId}`, {
method: 'DELETE',
}).then(response => {
dispatch(removeQuestion(questionId));
routerHistory.replace(`/`);
})
.catch(error => console.log(error));
};
};
I've checked numerous times to make sure the syntax and route is fine. questionId is also the correct question ID. However, no matter what I do, the Destroy method in the Questions controller won't recognize the request. I've checked the route in Rails and it exists. I don't get any errors, no request is ever sent to the server, and nothing is returned, not in terminal, the console, or anything.
This is the Github account: https://github.com/jwolfe890/react_project1
I'd really appreciate any insight anyone has. Thank you!
Your deleteQuestion method returns an anonymous function with a dispatch parameter which never seems to be called (Calling code). Only deleteQuestion is called but not the function returned by it.
Because it is called by a click handler I'd say you actually want something like this:
export const deleteQuestion = (questionId, routerHistory) => {
fetch(`${API_URL}/questions/${questionId}`, {
method: 'DELETE',
}).then(response => {
dispatch(removeQuestion(questionId));
routerHistory.replace(`/`);
})
.catch(error => console.log(error));
};
Or if you want to return the promise, you could of course change it to:
export const deleteQuestion = (questionId, routerHistory) => {
return fetch(`${API_URL}/questions/${questionId}`, {
method: 'DELETE',
}).then(response => {
dispatch(removeQuestion(questionId));
routerHistory.replace(`/`);
})
.catch(error => console.log(error));
};
If you want to dynamically inject the dispatch function, you could leave your original code, but would have to call the method like this:
deleteQuestion(this.state.question.id, history)(myDispatchMethod);
Can someone help me understand the following code? I found it here.
It takes advantage of the JQuery UI Autocomplete with a remote source. I've commented the code as best I can and a more precise question follows it.
$( "#city" ).autocomplete({
source: function( request, response ) {
//request is an objet which contains the user input so far
// response is a callback expecting an argument with the values to autocomplete with
$.ajax({
url: "http://ws.geonames.org/searchJSON", //where is script located
dataType: "jsonp", //type of data we send the script
data: { //what data do we send the script
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) { //CONFUSED!
response(
$.map(
data.geonames, function( item ) {
return {
label: item.name+(item.adminName1 ? ","+item.adminName1:"")+","+item.countryName,
value: item.name
}
}
)
);
}
});
}
});
As you can see, I don't understand the use of the success function and the response callback.
I know the success function literal is an AJAX option which is called when the AJAX query returns. In this case, it seems to encapsulate a call to the response callback? Which is defined where? I thought by definition of a callback, it should be called on its own?
Thanks!
The response object as defined by the documentation ("Overview" page):
A response callback, which expects a
single argument to contain the data to
suggest to the user. This data should
be filtered based on the provided
term, and can be in any of the formats
described above for simple local data
(String-Array or Object-Array with
label/value/both properties). It's
important when providing a custom
source callback to handle errors
during the request. You must always
call the response callback even if you
encounter an error. This ensures that
the widget always has the correct
state.
so, the 'response' argument is actually a callback, which must be called upon success of the ajax retrieval of autocomplete items.
Since your data will come back via AJAX, your code must update the widget manually. jQueryUI provides an argument as a function so that your code can do that update by calling the function.
You can see the response object defined in the declaration of the function used for the source option:
source: function( request, response )
You could even take the AJAX call out of the equation and do something like this:
source: function(request, response) {
response([{label:'foo', value: 'foo'},{label:'bar', value:'bar'}]);
}
Would immediately call the response callback with an array of label/value pairs for the widget.