You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Please note: as our current version is `2`, `onupgradeneeded`handler has a code branch for version `0`, suitable for users that come for the first time and have no database, and also for version `1`, for upgrades.
And then, only if `onupgradeneeded` handler finishes without errors, `openRequest.onsuccess` triggers, and the database is considered successfully opened.
94
95
95
96
删除数据库:
96
97
@@ -99,29 +100,34 @@ let deleteRequest = indexedDB.deleteDatabase(name)
```warn header="We can't open an older version of the database"
104
+
If the current user database has a higher version than in the `open` call, e.g. the existing DB version is `3`, and we try to `open(...2)`, then that's an error, `openRequest.onerror` triggers.
104
105
105
-
报错,触发 `openRequest.onerror`。
106
+
That's odd, but such thing may happen when a visitor loaded an outdated JavaScript code, e.g. from a proxy cache. So the code is old, but his database is new.
To protect from errors, we should check `db.version` and suggest him to reload the page. Use proper HTTP caching headers to avoid loading the old code, so that you'll never have such problem.
108
109
```
109
110
110
111
### 并行更新问题
111
112
112
113
提到版本控制,有一个相关的小问题。
113
114
114
-
一个用户在网页中打开了数据库为版本 1 的网站。
115
+
Let's say:
116
+
1. A visitor opened our site in a browser tab, with database version `1`.
117
+
2. Then we rolled out an update, so our code is newer.
118
+
3. And then the same visitor opens our site in another tab.
119
+
120
+
So there's a tab with an open connection to DB version `1`, while the second tab one attempts to update it to version `2` in its `upgradeneeded` handler.
In order to organize that, the `versionchange` event triggers in such case on the "outdated" database object. We should listen to it and close the old database connection (and probably suggest the visitor to reload the page, to load the updated code).
If we don't listen to `versionchange`event and don't close the old connection, then the second, new connection won't be made. The `openRequest` object will emit the `blocked` event instead of `success`. So the second tab won't work.
121
127
122
-
如果旧连接不关闭,新连接会被 `blocked` 事件阻塞,而不是 `success`。
128
+
Here's the code to correctly handle the parallel upgrade.
123
129
124
-
下面是执行此操作的代码:
130
+
It installs `onversionchange` handler after the database is opened, that closes the old connection:
0 commit comments