index.uts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * 在Web浏览器中打开指定的网页URL
  3. * @param url 要打开的网页地址,支持http、https等协议
  4. * @returns 返回操作结果,true表示成功,false表示失败
  5. */
  6. export function openWeb(url: string): boolean {
  7. // 参数验证:检查URL是否为空或无效
  8. if (url == null || url.trim() == "") {
  9. console.error("openWeb: URL参数不能为空");
  10. return false;
  11. }
  12. try {
  13. let trimmedUrl = url.trim();
  14. // 基本URL格式验证
  15. if (!trimmedUrl.includes(".") || trimmedUrl.length < 4) {
  16. console.error("openWeb: 无效的URL格式 -", trimmedUrl);
  17. return false;
  18. }
  19. // 如果URL不包含协议,默认添加https://
  20. if (!trimmedUrl.startsWith("http://") && !trimmedUrl.startsWith("https://") && !trimmedUrl.startsWith("//")) {
  21. trimmedUrl = "https://" + trimmedUrl;
  22. }
  23. // 在当前窗口中打开URL
  24. location.href = trimmedUrl;
  25. console.log("openWeb: 成功打开URL -", trimmedUrl);
  26. return true;
  27. } catch (e) {
  28. // 捕获可能的异常
  29. console.error("openWeb: 打开URL时发生错误 -", e);
  30. return false;
  31. }
  32. }