实现说明
input.showPicker 能力检测的核心是函数 openPicker。
使用要点
- 用到了
document,需要在浏览器环境运行,Node 里直接跑会缺 API。 - 守卫
typeof input.showPicker !== "function"成立时借助提前的return直接离开。 - 跑完文件,输出里会留下标记——
showPicker needs a browser DOM。
常见问题
「input.showPicker 能力检测」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
入口签名:function openPicker(input: HTMLInputElement)
核心语句
button?.addEventListener("click", () => {
if (input && openPicker(input)) {
input.focus();
}
});
if (error instanceof TypeError) return false; // no picker for this input type
throw error;
if (typeof input.showPicker !== "function") return false;
代码示例
// showPicker feature detection: typeof check first, then try/catch for
// inputs without a picker. It also throws NotAllowedError when the call is
// not inside a user gesture, so wire it to a click handler.
function openPicker(input: HTMLInputElement): boolean {
if (typeof input.showPicker !== "function") return false;
try {
input.showPicker();
return true;
} catch (error) {
if (error instanceof TypeError) return false; // no picker for this input type
throw error;
}
}
if (typeof document === "undefined") {
console.log("showPicker needs a browser DOM");
} else {
const input = document.querySelector<HTMLInputElement>("#meeting-date");
const button = document.querySelector<HTMLButtonElement>("#pick-button");
button?.addEventListener("click", () => {
if (input && openPicker(input)) {
input.focus();
}
});
console.log("showPicker available:", typeof input?.showPicker === "function");
}