How I Used Swift Script in Electron Browser Natively
Join the DZone community and get the full member experience.Join For Free
I initially solved this by writing OSAScript. The OSAScript was able to provide the list of open windows for Mac, but the main issue we identified during testing was CPU usage. As the OSAScript was running at an interval, it caused a 40–50% spike in CPU usage; thus, the solution was not acceptable.
After searching, I stumbled upon various solutions like:
- JsCocoa libraries: I tried integrating, but it did not work
All these approaches were either too cumbersome to use or would result in higher latency and increased app size.
Using SWIFT and
child_process.exec(): Finally, I decided to write a native SWIFT script using Cocoa to identify the process windows and tested it using Xcode Playground. The SWIFT script will output a JSON, which can be easily consumed and parsed. Once the testing is complete, I compiled it to create an executable using
swiftc sample.swift -o sample
This provided me with an executable
sample that can be executed using
./sample and output JSON.
The next step was to bundle it in Electron and consume it in
child_process.exec() method. In order to bundle, I placed this file in a folder, let's say
executable , and updated the copy script to include the content of this file while bundling the code. Once the executable is present inside the bundle, I provide the executable path to
child_process.exec() command. Using the callback from this command, I was successfully able to retrieve the SWIFT output JSON to make a decision in the Electron App.
This resulted in a reduction of the CPU overhead introduced by OSAScript to almost 0% from 40%
- Create binaries for any OS-specific executable like SWIFT for Mac
- Package this executable in your Electron application
child_processcommand to execute the packaged binary executable
- Consume a response in your Electron app to make a decision!
Opinions expressed by DZone contributors are their own.