如何使用javascript获取变量中的ip

时间:2019-03-02 09:15:20

标签: javascript

这是一个提供IP地址的api。

https://jsonip.com/

我想为我的应用程序使用变量中的IP地址。我可以得到这样的

window.onload = function () {
   var script = document.createElement("script");

   script.type = "text/javascript";

   script.src = "https://jsonip.com/?callback=DisplayIP";
   document.getElementsByTagName("head")[0].appendChild(script);
};
function DisplayIP(response) {
   document.getElementById("ipaddress").innerHTML = "Your IP Address is " + 
   response.ip;     
alert(response.ip);  // alerts  ip address
}

我必须将它与Sharpspring表单一起使用,因此上述方法无法与Sharpspring代码集成。我想要这样的东西

var ip = 'ip address';

为便于理解,这是Sharpspring的表单代码

<script type="text/javascript">
    var ss_form = {'account': 'MzawMDEzNjI0BwA', 'formID': 'SzQ1MTAzSEzSNTG2NNQ1STJN1k1KMjfVNTIzSwbCJKMUS2MA'};
    ss_form.width = '100%';
    ss_form.height = '1000';
    ss_form.domain = 'app-3QNBWW1ZDA.marketingautomation.services';
   ss_form.hidden = {'field_3270188034': 'ip address'}; //here I want to use that ip
</script>
<script type="text/javascript" src="https://koi-3QNBWW1ZDA.marketingautomation.services/client/form.js?ver=1.1.1"></script>

1 个答案:

答案 0 :(得分:1)

由于脚本要求使用document.write,因此我认为不可能在单个文档中使用。相反,您可以在初始页面加载时获取IP,然后再次加载页面 并同步创建ss_form对象,然后注入form.js

if (!sessionStorage.ip) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
  document.head.appendChild(script);

  window.DisplayIP = function DisplayIP(response) {
    sessionStorage.ip = response.ip;
    window.location.href = window.location.href;
  }
} else {
  const ip = sessionStorage.ip;
  sessionStorage.removeItem('ip');
  window.ss_form = {
    account: 'MzawMDEzNjI0BwA',
    formID: 'SzQ1MTAzSEzSNTG2NNQ1STJN1k1KMjfVNTIzSwbCJKMUS2MA',
    width: '100%',
    height: '1000',
    domain: 'app-3QNBWW1ZDA.marketingautomation.services',
    hidden: {
      'field_3270188034': ip
    }
  };
  const script = document.createElement('script');
  script.src = 'https://koi-3QNBWW1ZDA.marketingautomation.services/client/form.js?ver=1.1.1';
  document.head.appendChild(script);
}

(从HTML中删除当前的form.js