【问题标题】:window.open('', '_blank') doesn't open new tab on iOS onlywindow.open('', '_blank') 仅在 iOS 上不会打开新标签
【发布时间】:2020-09-18 07:32:06
【问题描述】:

我使用 _blank 调用了 window.open,它适用于除 iOS 之外的所有浏览器。在我的网络应用程序中,当我在 iOS 设备上单击“添加到购物车”按钮时,什么也没有发生,而在所有其他浏览器中,会打开一个新窗口。

const addProducts = (products) => {
    setProductsAdded(false);
    cService
      .add(products)
      .then(() => {
        setLoading(null);
        setProductsAdded(true);
        window.open(C_LINK, '_blank');
      })
      .catch(() => {
        setError('Error');
      });
  };

我找到了这个问题和答案,这似乎是同一个问题 - 但我是 Javascript 新手,不完全确定如何实现它:window.open(url, '_blank'); not working on iMac/Safari

所以我的第一个问题是,我是否认为我刚才提到的问题和答案可能是同一个问题?我的第二个问题是,如果我要尝试实现上一个问题中提到的解决方案,我会修改现有功能还是将其分开?我将在哪里设置 window.open()?有人可以解释一下“myService”到底是什么吗?感谢您的帮助。

【问题讨论】:

  • 是的,可能是这样,尤其是在执行之前的代码时。
  • 您想在新窗口中打开链接吗?

标签: javascript ios mobile-safari


【解决方案1】:

这就是我在 React 应用程序上使用它的方式。
使用 onClick 处理程序的唯一方法。在我的用例中,我需要通过 API 调用来获取 URL。如果 onClick 内部发生任何其他事情,Safari 会阻止 window.open()。

我所做的解决方法是使用状态来管理我的 URL,在 useEffet() 的帮助下根据其他依赖项动态更新它。并保持 URL 始终更新,因此一旦单击按钮。它总是从州提供更新的 URL。

const [cart, setCart] = useFetchCart();
const [checkoutLoading, setcheckoutLoading] = useState(false);

你是我的州。

useEffect(() => {

const updateCheckoutURL = async () => {
  setcheckoutLoading(true);
  const newCheckoutURL = await helpers.shop.checkout(cart);
  setCheckoutURL(newCheckoutURL);
  setcheckoutLoading(false);
}
updateCheckoutURL();
}, [cart]);

这个 useEffect() 确保 URL 总是被更新。

checkoutLoading ? <Spinner size={20} /> : <button onClick={() => { window.open(checkoutURL) }} className="checkoutButton">Checkout</button>

最后是使用它的按钮。

【讨论】:

    【解决方案2】:

    为此,您需要将 URL 绑定到元素 onclick 事件。

    请按照代码。在您的 HTML 中添加此按钮。

    <button class='btn' id="btnClick" onclick='window.open("https://www.google.com", "_blank");' style='position: absolute;top: 0;display: none'>Open Google search</button>
    

    在 onclick 事件中替换您的链接。现在使用 javascript 触发点击事件。

    更改window.open(C_LINK, '_blank');

    document.getElementById("btnClick").click()
    

    REFERENCE

    【讨论】:

    • 谢谢 - 我也很高兴看到这个。
    【解决方案3】:

    我以前没有尝试过,但是从 SO 答案中实现解决方案看起来像这样:

    // Open a new window and save a reference to it
    var newWindow = window.open();
    
    const addProducts = (products) => {
        setProductsAdded(false);
        cService
          .add(products)
          .then(() => {
            setLoading(null);
            setProductsAdded(true);
    
            // Set the URL of the new window
            newWindow.location = C_LINK;
          })
          .catch(() => {
            setError('Error');
          });
      };
    

    在另一篇文章中,myService 是一个不存在的返回 URL 的示例服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-04
      • 2012-06-17
      • 2015-06-09
      • 2017-09-29
      • 1970-01-01
      • 2014-07-24
      • 2016-02-12
      相关资源
      最近更新 更多