我通过实验获得了更多经验,所以这是我到目前为止所学到的。
如我所想,我们可以通过document.referrer(浏览器)和req.headers.referer(服务器)来解析referrer。
因此,可以检测当前引荐来源网址是否与我们的托管服务器不同,在这种情况下,我们知道查询来自 iframe。
当您想从服务器端了解您网站中的页面是否已通过同一网站中的 iframe 加载时,这会变得更加棘手。在这种情况下,无法自动检测我们是否从 iframe 运行页面。
例如,如果您在页面 /index 上有一个加载 /page2 页面的 iframe,那么您无法从服务器端知道 /page2 是从 iframe(在 /index 上)加载还是从导航加载到 /page2。
这就是为什么人们说无法从服务器端知道页面是否通过 iframe 加载。因为不确定。
现在,我的实际需求有点不同。我需要知道我的/page2 是否是从我自己的另一个域(跨域)加载的,这很容易知道,因为无论是在服务器端还是浏览器端,引用者都会与我自己的域不同。
我的集成测试有点复杂,因为我有一个 /tests/iframeIntegration 页面,其中包含一个 iframe,它从同一域加载另一个页面 /page2。 (相对网址)
关键是要测试 iframe 集成是否按预期工作,因为它在同一个域上运行,我无法确定我是否通过 iframe 加载它。
对于这种特殊情况,我在网址中添加了/page2?iframe=true。这是我发现的最简单的通用解决方法(浏览器 + 服务器)。
以下是一些实用程序脚本:
import { isBrowser } from '@unly/utils';
import includes from 'lodash.includes';
/**
* Resolves whether the current web page is running as an iframe from another page
*
* Iframes are only detectable on the client-side
* Also, using iframe=true as search parameter forces iframe mode, it's handy when using an iframe from the same domain
* (because same-domain iframes aren't detected when comparing window.parent and window.top since it's the same window)
*
* @return {boolean}
* @see https://stackoverflow.com/a/326076/2391795
*/
export const isRunningInIframe = (): boolean => {
if (isBrowser()) {
try {
return window.self !== window.top || includes(document.location.search, 'iframe=true');
} catch (e) {
return null; // Can't tell
}
} else {
return null; // Can't tell
}
};
/**
* Resolve the iframe's referrer (the url of the website the iframe was created)
*
* Helpful to know which of our customer use our app through an iframe, and analyse usage
* May not always work due to security concerns
*
* @return {string}
* @see https://stackoverflow.com/a/19438406/2391795
*/
export const getIframeReferrer = (): string => {
if (isRunningInIframe()) {
try {
return document.referrer || null;
} catch (e) {
return null;
}
} else {
return null;
}
};