简体   繁体   English

使用PHP脚本执行JS <script> tag on the homepage only

[英]Use a PHP script to execute a JS <script> tag on the homepage only

I am trying to create a statement in PHP that will make a survey monkey popup appear on the homepage of a website and not on the other pages. 我正在尝试在PHP中创建一条语句,使调查猴子弹出窗口出现在网站的主页上而不是其他页面上。

I've tried the below code and different variations of it to try and get it to work. 我已经尝试了以下代码及其各种变体,以使其正常工作。 I can add the popup to the entire site by just putting the element into the of the website but when I try to get it to appear only on the homepage, nothing shows up at all. 我可以通过将元素添加到整个网站中来将弹出窗口添加到整个网站,但是当我尝试使其仅显示在首页上时,则什么也没有显示。

I've tried it using just one 'echo' instead of splitting it into three and also using /index.php instead of /. 我已经尝试过只使用一个'echo'而不是将其拆分为三个,并且还使用/index.php而不是/。

<?php
if ($_SERVER["SCRIPT_NAME"] == '/') { 
  echo '<script>';
  echo '(function(t,e,s,o){var n,a,c;t.SMCX=t.SMCX||[],e.getElementById(o)||(n=e.getElementsByTagName(s),a=n[n.length-1],c=e.createElement(s),c.type="text/javascript",c.async=!0,c.id=o,c.src=["https:"===location.protocol?"https://":"http://","widget.surveymonkey.com/collect/website/js/tRaiETqnLgj758hTBazgd_2Fw5nxAtNDAAqLsYqzVv_2FShi5yryjY3psD6EYInvUCYX.js"].join(""),a.parentNode.insertBefore(c,a))})(window,document,"script","smcx-sdk");';
  echo '</script>';
 }

?>

I have found some similar questions on here but none that quite fit my situation, I've also tried out some of their answers recommendation but they don't seem to work. 我在这里找到了一些类似的问题,但没有一个完全适合我的情况,我也尝试了一些他们的答案建议,但它们似乎没有用。

Any help would be greatly appreciated, I feel like it's something so simple and I'm just complicating matters. 任何帮助将不胜感激,我觉得这很简单,只是使事情变得复杂。 Hopefully I've provided enough information for you all! 希望我为大家提供了足够的信息!

PHP solution: PHP解决方案:

$active_location = $_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]; 
$host_name = $_SERVER['HTTP_HOST']; 
if ($active_location == $host_name || $active_location == $host_name.'/'){
//stuff you want to do
}

the $active_location will return the current full url without the ssl sertivication the $host_name wil give the hostname without ssl. $active_location将返回不带ssl引文的当前完整URL, $host_name给出不带ssl的主机名。 if they are the same the code will run. 如果它们相同,则代码将运行。

The OR (||) statemant is because in some cases the homepage will will have an / without you seeing it, if you don't put the statment the code will not run is some cases. OR (||)是因为在某些情况下主页上会有一个/而您却看不到它,如果您不输入说明,则在某些情况下代码将无法运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM