window.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. interface OpenWindowOptions {
  2. noopener?: boolean;
  3. noreferrer?: boolean;
  4. target?: '_blank' | '_parent' | '_self' | '_top' | string;
  5. }
  6. /**
  7. * 新窗口打开URL。
  8. *
  9. * @param url - 需要打开的网址。
  10. * @param options - 打开窗口的选项。
  11. */
  12. function openWindow(url: string, options: OpenWindowOptions = {}): void {
  13. // 解构并设置默认值
  14. const { noopener = true, noreferrer = true, target = '_blank' } = options;
  15. // 基于选项创建特性字符串
  16. const features = [noopener && 'noopener=yes', noreferrer && 'noreferrer=yes']
  17. .filter(Boolean)
  18. .join(',');
  19. // 打开窗口
  20. window.open(url, target, features);
  21. }
  22. /**
  23. * 在新窗口中打开路由。
  24. * @param path
  25. */
  26. function openRouteInNewWindow(path: string) {
  27. const { hash, origin } = location;
  28. const fullPath = path.startsWith('/') ? path : `/${path}`;
  29. const url = `${origin}${hash && !fullPath.startsWith('/#') ? '/#' : ''}${fullPath}`;
  30. openWindow(url, { target: '_blank' });
  31. }
  32. export { openRouteInNewWindow, openWindow };