有一个接口,必须得传用户IP参数,然后LWC还不能直接获取P地址,上网上查,说是得用VF Page才能获取用户的IP地址,于是就有了在LWC中镶嵌VF Page的问题。
这个VF Page是一个功能性的页面,没有需要显示出来的内容,该VF Page在用户的眼里是不可见的。
首先创建VF Page,这个VF Page得借助一个Apex类能获取到用户IP。
java
public without sharing class GuestUserIPController {
public String ipAddress { get; set; }
public GuestUserIPController() {
// 从当前页面的请求头中获取IP地址
Map<String, String> headers = ApexPages.currentPage().getHeaders();
// 按优先级尝试多个请求头字段,以应对不同的网络环境
ipAddress = headers.get('True-Client-IP');
if (String.isEmpty(ipAddress)) {
ipAddress = headers.get('X-Salesforce-SIP');
}
if (String.isEmpty(ipAddress)) {
ipAddress = headers.get('X-Forwarded-For');
}
// 如果都为空,可以设置一个默认值或留空
if (String.isEmpty(ipAddress)) {
ipAddress = 'IP not available';
}
}
}
html
<apex:page controller="GuestUserIPController" showHeader="false" standardStylesheets="false" sidebar="false">
<ipAddress>{!ipAddress}</ipAddress>
<script>
// Get the IP address from the Visualforce page
var ipAddress = document.querySelector('ipAddress').textContent;
parent.postMessage({
type: 'ipAddress',
ip: ipAddress
}, '*');
console.log('IP address sent to parent window: ' + ipAddress);
</script>
</apex:page>
页面获得IP之后,将向LWC发布消息,把ip传出去。
然后LWC页面用iframe把这个VF Page页面镶嵌进去
html
<div style="display:none;">
<iframe src={vfPageUrl}></iframe>
</div>
在LWC的 connectedCallback方法中添加收取ip的方法
javascript
window.onmessage = (event) => {
const data = event.data;
if (data.type === 'ipAddress'){
this.ipAddress = data.ip;
console.log('Received IP Address from iframe:', this.ipAddress);
}
}
这样就可以获取浏览用户的IP了