← 中文资源

简体中文版本

input.showPicker 能力检测

点击时打开日期输入的浏览器原生选择器:先检测 showPicker 是否存在,再用 try/catch 捕获无选择器类型抛出的 TypeError,并保证调用发生在用户手势内。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

showPicker needs a browser DOM

实现说明

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");
}