当 iframe URL 无法加载时停止花式框 3 打开

Stop fancy box 3 opening when iframe URL fails to load

如果无法使用 Fancybox 3 加载,我希望能够重定向到给定的 URL。用户提供 URL,因此它可能是一个 youtube 视频,图像,或其他一些任意 link。在 Google Doc 之类的情况下,google 会阻止您将它们加载到 iframe 中,因此我想捕获该错误并完全停止加载精美的框查看器,而是重定向到URL 直接在浏览器中。我可以让它正常工作,但我似乎无法阻止在重定向发生之前显示精美的框对话框:

$.fancybox.defaults.afterLoad = (instance, current) ->
  if current.hasError
    window.location = current.src
    instance.close()

我试过返回 false。

这是迄今为止我想到的最好的:

$.fancybox.defaults.defaultType = 'iframe'
$.fancybox.defaults.beforeLoad = (instance, current) ->
  $.ajax
    url: current.src
    method: 'HEAD'
  .catch ->
    window.location = current.src
    instance.close()

如果 URL 未通过所有其他测试(如图像和视频),则默认值为 ajax,因此我们需要先将其切换为 iframe。然后我做一个 ajax HEAD 调用,看看结果是否成功,如果没有,我们可以重定向到 src。 instance.close() 是我能找到的阻止 fancybox 加载的最佳方法(如果这是一个 slideshow/gallery,它可能已经被加载)。在页面之前有一个短暂的闪光然后重定向到 URL.

正如@misorude 所提到的,没有办法检测 iframe 是否未能针对跨站点请求加载。最后我决定完全取消预览场外 links 并像这样进行重定向:

$.fancybox.defaults.afterLoad = (instance, slide) ->
  if !slide.redirecting && slide.contentType == 'html'
    slide.redirecting = true
    message = """<div class="fancybox-error"><p>Redirecting...</p></div>"""
    instance.setContent slide, message
    window.location = slide.src

这会显示一个很好的重定向消息,然后通过浏览器将用户发送到 link。 contentType 只有 html 当它不是 imagevideomap 等...来自其他媒体类型插件时。这意味着 fancybox 仍然可以毫无问题地显示 youtube links,即使它们是基于 iframe 和 html 的。