确定请求是通过浏览器 bookmark/favorite 还是 link?

Determine if a request was via a browser bookmark/favorite vs a link?

假设我在一个网站上查看 https://whateverxyz.com/index 的主页。那我要么

服务器能否区分请求是来自 A 还是 Bapp1.html 上的客户端 JavaScript 运行 可以区分吗?

恐怕,你是查不出来的! 它只能在浏览器扩展中访问。

Citate from your question:

  • Can the server tell the difference between whether request was from A or B?
  • Can client-side JavaScript running on app1.html tell the difference?

在这两种情况下都无法检测到差异。

官方资源怎么说?

Citate from RFC 7231 - Hypertext Transfer Protocol (HTTP/1.1)

If the target URI was obtained from a source that does not have its own URI (e.g., input from the user keyboard, or an entry within the user's bookmarks/favorites), the user agent MUST either exclude the Referer field or send it with a value of "about:blank".

The Referer field has the potential to reveal information about the request context or browsing history of the user, which is a privacy concern if the referring resource's identifier reveals personal information (such as an account name) or a resource that is supposed to be confidential (such as behind a firewall or internal to a secured service). Most general-purpose user agents do not send the Referer header field when the referring resource is a local "file" or "data" URI. A user agent MUST NOT send a Referer header field in an unsecured HTTP request if the referring page was received with a secure protocol. See Section 9.4 for additional security considerations.

了解更多信息:

备选方案

但是你可以在客户端做一些事情。在页面 https://whateverxyz.com/index 中,您可以在 JavaScript 中编写一个侦听器,用于检测此页面 link 上的所有点击。在点击事件中,您可以在 cookie 中写入 link URLtime,一个IndexedDBlocalStorage。然后在页面 https://whateverxyz.com/app1.html 你必须阅读这些信息。如果此信息不是未定义的,则它来自 link,而在所有其他情况下,它来自书签(或者可能是在地址栏或其他任何地方提示)。

查看相关问题:

  • How to client-side detect when a page is bookmarked?
  • How to detect if a link already is in the user's bookmarks?
  • Is there a way to know if someone has bookmarked your website?

您可以在页面加载后设置查询参数JavaScript。 (使用 history.pushState 所以它不会重新加载)。喜欢:

history.pushState({}, "", "?bookmarked")

因此,当导航来自书签时,它带有 ?bookmarked 参数,而当它是常规导航时,您将在没有任何参数的情况下获得它。

Working example, Code for example

编辑:正如评论中所指出的,这种方法有两个问题。

  1. 浏览器中的 URL 栏将始终包含 ?bookmarked 查询参数。
  2. 重新加载时,服务器将获得 ?bookmarked,即使它不是来自书签。 (可以按照 this question 的答案中指出的方法解决)