跪拜 Guibai
← Back to the summary

Run JavaScript on iPhone: Scriptable Plus a 3-Line Live-Reload Script

Title: iOS Development Plan (Part 1) - Running JavaScript Scripts on iOS with Scriptable Author: Vic_wkx

Aside

Recently I've felt like I'm no longer a programmer. My daily workflow is to open an AI tool and assign tasks to it.

That's not programming; it's more like making wishes to AI.

My brain has started to slack off as well. I brought this up with friends over lunch, and one said: "The current work environment is unhealthy. We're not producing any value in it."

That was a wake-up call. At middle age, it's very easy to rest on a little success. Once you stop creating value, being phased out of society begins. So I decided I shouldn't slack off. I should keep working on technology, writing code, and always being someone who thinks hard.

My friend also mentioned that the tech-training industry is struggling now, because AI is the best trainer there is. AI is learned, humble, and available one-on-one. When learning, every student has different points of confusion, and AI can precisely answer each student's unique questions.

For example, when I study, I care a lot about understanding where a concept comes from. A simple example: I recently read a book by a forensic doctor called The Truth Won't Stay Silent, and it mentioned "shock". I wondered where that name came from. Rest? Restraint? I can't accept treating it as a given, fixed concept.

"Confusion that does not seek a teacher remains confusion forever."

Answering this kind of question used to be difficult, but now:

Me: Where does the name "shock" come from? Rest? Restraint?

AI: "Shock" is actually a phonetic transliteration of the English "shock", not an abbreviation for "rest" (休) + "restraint" (克), but the translator did manage to cover both sound and meaning:

  1. Etymology (transliteration): It comes from English shock (which goes back to the French choc, meaning "violent impact, shaking"). In 1743, British doctors translating the French surgeon Le Dran's work on gunshot wounds first used shock to describe the sudden collapse of bodily functions after a severe injury.
  2. Clever character choice (meaningful shading): When transliterating into Chinese, they didn't use meaningless characters like "勺克", but chose "休" (to stop, to fail, as in "休止") and "克" (to suppress, critical), which vividly match the pathology of shock: blood circulation drops sharply and vital functions seem to be forcibly paused.

Suddenly it all became clear.

Since AI works so well as a teacher, I shouldn't let this secret manual go to waste. So I decided to learn some iOS development.

Let's start here.

Scriptable

Scriptable is an iOS app that lets an iPhone run JS scripts.

App link: https://apps.apple.com/cn/app/scriptable/id1405459188

For example, a simple JS script:

let alert = new Alert();
alert.title = "Hello";
alert.message = "Welcome to my script!";
alert.addAction("OK");
await alert.present();

The result:

0bb1f47d2c26118f2e9b03087243c482.jpg

You can also add scripts to the home screen as widgets:

Long-press an empty area of the home screen, tap Edit at the top-left, tap Add Widget:

lQDPJwujWk434E3NBQDNAk-w6cfTVJHw_0YK1cwQxx63AA_591_1280.jpg

Find Scriptable, tap Add Widget:

7b6e4a1099f0023ff7f9fef6b51bd974.jpg

Long-press the widget to select which script to run:

0f70787b46e1d163f430dddd3c9c4993.jpg

Apps written this way are called Progressive Web Apps (PWAs) - apps developed with web technologies (HTML/CSS/JS) that can still install to the phone home screen like native apps.

Q: Here's how I currently write Scriptable scripts:

  1. Write in VS Code on my computer, copy-paste into the DingTalk app (installed on both devices), then copy from DingTalk to Scriptable on the phone and run it. Making changes is very annoying.
  2. Edit JS on the phone - very unfriendly.

I'd like to write JS on the computer and quickly run it on the phone. Is there a good way?

A: LAN real-time hot reload (the most comfortable: Ctrl+S on the computer, one tap on the phone to run)

If the phone and computer are on the same LAN:

  1. Computer: In the folder containing the JS, open a terminal and start a simple built-in server (e.g. python -m http.server 8080).

  2. Phone: Create a new script in Scriptable with just these 3 lines (you'll never need to change them):

     const ip = "Your computer's LAN IP" // Replace with your computer's LAN IP
     const req = new Request(`http://${ip}:8080/my-script.js?t=${Date.now()}`)
     const code = await req.loadString()
     await eval(`(async () => {\n${code}\n})()`) // directly run the latest code pulled from the computer
    

Q: How do I confirm the server on the computer started successfully?

Work through these 3 steps from easiest to hardest:

1. Check the terminal output

After pressing Enter, if the terminal shows something like the line below and doesn't exit with an error (the cursor stays waiting), it started successfully:

Serving HTTP on :: port 8080 (http://[::]:8080/) ...
2. Verify in the computer's browser

Open the computer's browser and visit http://localhost:8080:

3. Verify in the phone's browser (most critical - tests LAN connectivity)
  1. Find the computer's IP: Open another terminal window on the computer and run ipconfig. Find the IPv4 Address (e.g. 192.168.1.100 or 10.x.x.x).

  2. Access from the phone: In the phone's Safari, open http://YourComputerIP:8080.

    • If the phone also shows the file list and the computer terminal prints an access log line ("GET / HTTP/1.1" 200), everything is connected!
    • If the computer can open it but the phone just keeps spinning, then the company network is isolating devices, or Windows Firewall is blocking it.

Q: Explain the script running on the phone

  1. Build the request and bypass the cache (lines 1-2):

    A template string `...${variable}...` concatenates the computer's LAN address.

    Appending ?t=${Date.now()} (current millisecond timestamp) makes each request URL different, forcefully bypassing the HTTP cache at the iOS system level, ensuring the latest saved file is fetched from the computer every time. Without this tail, the phone wouldn't pick up changes immediately after the computer is edited.

  2. Fetch the remote source code (line 3):

    await req.loadString() downloads my-script.js from the computer to the phone's memory as a plain-text string.

  3. Build the async environment and execute dynamically (line 4):

    • eval() can take a string and execute it as JS code dynamically, but native eval() runs in a synchronous context by default and doesn't support await at the top level (e.g. await alert.present() would throw a syntax error).
    • So an immediately-invoked async arrow function (async () => { ... })() wraps the code, perfectly recreating Scriptable's native async execution environment.
Comments

Top 1 of 3 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

This trick is really handy; the hot-reload part is the key. Change on the computer, and the phone runs it right away — this is what learning iOS should look like.

Vic_wkx

Yes, and another trick: while the phone is running, when printing logs for debugging, transmit the logs over the LAN to a file on the computer, so the phone runs while the computer shows the logs — even smoother for development. I'll add this content later.

Vic_wkx

Updated the way to view phone runtime logs on the computer: https://juejin.cn/spost/7712284408648695843