介绍

为了帮助快速启动和运行优化方案,提供了一些代码示例。

本页内容

  • 事件跟踪: 请参阅事件跟踪部分,该部分说明了所有可用于跟踪事件的API。

  • 自定义JS条件: 如果在客户端上公开第一方或第三方数据,则可以使用云眼的自定义JS条件将数据移入不同的受众。

  • 高级用例: 这些高级用例将帮助最大程度地利用优化方案Javascript和优化版本Javascript的功能。

  • 条件激活: 有时候,需要在页面或屏幕的某些部分加载后动态启动云眼优化方案。请阅读云眼条件激活部分,了解有关如何控制优化方案启动的更多信息。

  • 帮助函数: 很多时候,有必要在云眼优化方案中使用getter和setter方法来更好地与网站进行交互。这个帮助函数列表包含的函数常用在优化方案Javascript和优化版本Javascript功能中。

  • 互斥: 除了正常的运行优化方案,也可以互斥地运行每个优化方案。

  • 单页应用程序: 在传统网站上,当访问者点击链接时,链接通常会导致一个新的URL并加载一个全新的页面。在单页面应用程序中,整个页面不会重新加载; 相反,某些内容会在当前网址中更改,加载和渲染。查看云眼单页应用程序部分,以帮助适应单页应用程序的行为。

  • 集成: 无论是要与第三方分析平台的集成,还是要通过云眼进行WordPress标题测试,这些集成代码示例将帮助。

  • 优化版本代码: 如果想编写自己的优化版本代码,而不是使用云眼可视化编辑器,请查看云眼优化版本代码部分,该部分通过示例代码介绍了优化版本代码的编写格式。

事件跟踪

这些代码示例可以用于在特定用户操作后跟踪目标。大部分代码示例常应用在优化方案Javascript或优化版本Javascript功能中。

滚动深度

此功能检查每一次网页发生滚动后,网页是否滚动到特定区域中。在此示例中,当访问者滚动到页面的25%,50%,75%和100%区域时,自定义事件将被触发。在目标菜单中,需要创建与以下事件相对应的自定义事件目标(例如,“scroll25”,用于滚动页面的25%)。

Javascript代码示例

/*
 * Usage
 *    This function fires custom events at different scroll depth milestones.
 */

  // Variables to prevent continuous firing of custom events

  var scrollTwentyFive = true;
  var scrollFifty = true;
  var scrollSeventyFive = true;
  var scrollOneHundred = true;

  // Create the scrollPercentage

  $(window).bind('scroll', function() {
      window.scrollPercent = ($(window).scrollTop() / ($(document).height() - $(window).height())) * 100;

      // Conditional code we'll use to fire events based on scrollPercentage.

      if (window.scrollPercent >= 25 && scrollTwentyFive) {
          window['eyeofcloud'] = window['eyeofcloud'] || [];
          window.eyeofcloud.push(["trackEvent", "scroll25"]);
          scrollTwentyFive = false;
      }

      if (window.scrollPercent >= 50 && scrollFifty) {
          window['eyeofcloud'] = window['eyeofcloud'] || [];
          window.eyeofcloud.push(["trackEvent", "scroll50"]);
          scrollFifty = false;
      }

      if (window.scrollPercent >= 75 && scrollSeventyFive) {
          window['eyeofcloud'] = window['eyeofcloud'] || [];
          window.eyeofcloud.push(["trackEvent", "scroll75"]);
          scrollSeventyFive = false;
      }

      if (window.scrollPercent >= 100 && scrollOneHundred) {
          window['eyeofcloud'] = window['eyeofcloud'] || [];
          window.eyeofcloud.push(["trackEvent", "scroll100"]);
          scrollOneHundred = false;
      }

  });

自定义JS条件

这些代码示例可以在受众条件的自定义Javascript功能中使用。请记住,此条件下的最后一行Javascript代码的返回值类型必须是布尔值。

在页面中获取数据

这是使用Javascript访问在云眼SDK之外定义的对象的示例。请注意,变量必须在云眼SDK之前被声明,确保在执行受众条件匹配检查之前被定义。

Javascript代码示例

/*
 * Usage
 *    Example showing how to reference a variable defined natively on the page from inside Eyeofcloud.
 *
 */

 // Audience condition example checking the 'category' property of the 'exampleObject'
 window.exampleObject['category'] == 'shirts';

通过元值定位目标页面

以下条件将仅在页面上存在某个元值时运行。

Javascript代码示例

/*
 * Usage
 * Replace "desired_value" with the name of the meta value you're testing for.
 */

 $('meta[name="desired_value"]').length > 0

根据屏幕大小定位访问者

第一个条件将确保仅当屏幕宽度大于1400像素且高度大于800像素时,优化方案才会运行。第二个条件将确保仅在视口宽度介于320和480像素之间,高度小于或等于640像素的情况下运行优化方案。

Javascript代码示例

/*
 * Usage
 *  Specifies window size (in pixels) to target visitors.
 */

 //target desktop viewports
 //matches CSS media queries for height/width or max/min-height or -width
 window.innerWidth > 1400 && window.innerHeight > 800

 //target mobile phones
 //matches CSS media queries using device-height and device-width
 screen.width >= 320 && screen.width <= 480 && screen.height <= 640

定位指定的用户代理

以下条件仅适用于正在使用Google Chrome浏览器的访问者。

Javascript代码示例

/*
 * Usage
 *  Targets visitors based on user-agent.
 */

 window.navigator.userAgent.indexOf("Chrome") !== -1

高级用例

这些代码示例可以在优化方案Javascript或优化版本Javascript功能中使用,以满足对云眼的高级使用需求。

指定代码的运行次数

这个用法可以指定在优化方案中执行特定代码的次数。

例如,只想在前3次访问时向访问者显示弹出式窗口。在这种情况下,可以使用优化方案Javascript或优化版本Javascript功能。

Javascript代码示例


/*
 * Usage
 *   The following allows you to set a limit on the number of times a Code Block will execute for any given visitor.
 */

 // the number of times the code should execute for a given visitor
 var limit = 3;
 // the number of days the evaluation limit should last
 var days = 180;
 // name of the cookie we use as the counter
 var cookieName = 'counterCookie';

 // function to fetch cookie values
 var getCookie = function(name) {
   var match = document.cookie.match(name+'=([^;]*)');
   return match ? match[1] : undefined;
 };

 // function to create cookies
  var setCookie = function(c_name,value,exdays,c_domain) {
    c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";";
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value + ";" + c_domain + "path=/";
  }

 // logic that counts and limits number of times code can evaluate for given visitor
 if (!getCookie(cookieName)) {
   setCookie(cookieName, 1, days, window.location.hostname);
 } else {
   var numberPops = parseInt(getCookie(cookieName)) + 1;
   setCookie(cookieName, numberPops, days, window.location.hostname);
 }

 if (getCookie(cookieName) <= limit) {
  // INSERT code to evaluate HERE
 }

更改页面标题

此用法可以在访客与浏览器选项卡交互时,修改浏览器选项卡的文本。当访客移动鼠标指针到选项卡上时,在选项卡中显示标题A,当访客切换到不同的浏览器选项卡或窗口时,选项卡显示标题B。

Javascript代码示例


/*
 * Usage
 *   The following code will modify the title of the browser tab on the "blur" event and change it back to the original on the "focus" event.
 *
 */

 // store the original tab title
 var origTitle = document.title;

 // function to change title when focusing on tab
 function oldTitle() {
   document.title = origTitle;
 }

 // function to change title when un-focusing on tab
 function newTitle() {
   document.title = 'HELLO WORLD';
 }

 // bind functions to blur and focus events
 window.onblur = newTitle;
 window.onfocus = oldTitle;

获取离线转换参数

此用法循环遍历云眼SDK数据对象,从而获取构建离线转化URL所需的信息。请注意,此代码仅在优化方案正在运行的网页上有效。

Javascript代码示例

/*
 * Usage
 *    Loops through the Eyeofcloud Data Object to return the information necessary to construct the off-line conversions URL.
 *
 */

 // grab the endUserID from the Eyeofcloud Cookie
 var endUserId = document.cookie.match('eyeofcloudEndUserId=([^;]*)')[1];

 for (var i=0; i < eyeofcloud.activeExperiments.length; i++) {
   var experimentID = eyeofcloud.activeExperiments[i];
   var variationID = eyeofcloud.variationIdsMap[experimentID];
   var variationName = eyeofcloud.variationNamesMap[experimentID];
   // code to pass this data to your backend should go here
 }

条件激活

条件激活模式是灵活而且强大的激活优化方案的办法。有两种使用方式:一是通过轮询,输入条件,一旦条件为真,SDK就激活优化方案。二是使用回调函数。下面详细地描述了这两种使用方式,并且还附加了使用每种方式的几个例子。

根据输入的代码,云眼将自动确定是采用轮询还是回调函数。

轮询

如果输入的代码不是函数类型,则将每隔50ms检查一次代码,并在代码输出为真时激活优化方案。云眼将检查动作放在在try / catch代码块中,如果输入代码运行抛出异常或者错误,则云眼将假定代码输出为false,并且继续轮询。

回调函数

如果输入的代码是一个函数,云眼将向该函数传递一个 activate 函数和一个 options 对象,然后立即调用它。回调函数不需要返回任何值,回调函数应该在条件满足时调用activate()方法。请注意,由于在云眼SDK加载时就立即调用此函数,所以在此函数内引用的任何函数或变量都应在调用此函数前被定义且可获取。

注意: 无论使用哪种方法,记住这只是激活条件。访客仍然需要满足业务URL和受众条件,才能实际进入优化方案,被分配至优化版本。

Javascript代码示例


/*
 * Usage Option #1 - Polling
 *   Eyeofcloud will poll for the code condition to be true if the JavaScript
 *   entered does not evaluate to a function type.
 *
 *  Note: Eyeofcloud will evaluate this code in a try/catch block, meaning
 *  if your expression errors, it will be evaluated as false
 */

 [Code whose last line evaluates to true/false, just like custom JS targeting]


/*
 * Usage Option #2 - Callback Function
 *   Eyeofcloud will call the function entered immediately if the JavaScript entered
 *   does evaluate to a function type.
 *
 * @param {Function} activate - Activate this experiment
 * @param {Object=}  options {
 *                     isActive : {Boolean} - Indicates if this experiment is active
 *                     experimentId : {Integer} - This experiment's Id
 *                   }
 *
 *  Note: Eyeofcloud will call this function immediately when the snippet loads, so make
 *  sure any functions referenced are defined at that time.
 */

 function(activate, options) {
   // Do logic and call `activate()` when appropriate
 }

轮询 - 检查元标签的值

根据元标签的值激活优化方案,请使用jQuery选择元标签的内容,并检查它们的值。

HTML代码示例

<meta name="keywords" content="movies,games,videos,photos"/>

Javascript代码示例

/*
 * Condition: Activate when the description meta tag contains 'sports', 'games', or 'puzzles'
 * Type: Polling
 */

 (/sports|games|puzzles/).test($('meta[name=keywords]').attr('content'))

轮询 - 检查JavaScript的值

根据JavaScript变量的值激活试验,只需输入要检查的条件即可。

Javascript代码示例

/*
 * Condition: Activate when the Omniture eVar 33 contains 'product'
 * Type: Polling
 */

 window.s.eVar33.indexOf('product') != -1

轮询 - DOM元素

根据DOM元素的存在激活试验,只需使用jQuery选择该元素,并检查结果的长度。

Javascript代码示例

/*
 * Condition: Activate when the green button DOM element appears
 * Type: Polling
 */

 $('button.green').length > 0

回调函数 - 按钮

在按下按钮时激活优化方案,请使用jQuery 将一个 clickmousedown 事件绑定到该元素,并在该事件触发时激活优化方案。

Javascript代码示例

/*
 * Condition: Activate when a button is clicked
 * Type: Callback function
 */

 function(activate, options) {
   $('html').delegate('#btn', 'mousedown', function() {
     activate();
   });
 }

回调函数 - AJAX响应

在有些情况下,试验需要在一个AJAX请求返回之后才能激活,那么就可以利用 ajaxComplete 这个函数来监听请求。如果请求的内容中包含了试验所需要的东西,就激活试验。

需要注意的是,如果AJAX请求在发送时,将 global 参数设置为false,会导致 ajaxComplete 事件不会触发。更多信息,请参阅jQuery的文档。

Javascript代码示例

/*
 * Condition: Activate when an AJAX call contains the element that should be changed
 * Type: Callback function
 */

 function(activate, options) {
   $(document).ajaxComplete(function(event, xhr, settings) {
     if (xhr.responseText.indexOf('rightRailModule') != -1) {
       activate();
     }
   });
 }

回调函数 - Angular的页面切换

如果想要在Augular应用的location改变时激活试验,可以在 $locationChangeSuccess 上设置一个回调函数,如果页面符合某种条件,则激活试验。

注意:并不是所有Angular应用的实现都采用了这种方式,所以在有些情况下这种方式可能无法正常工作。这个例子只适用使用了Angular内置方法的情况。

Javascript代码示例

/*
 * Condition: Activate when an Angular.js application successfully changes location
 * Type: Callback function
 */

 function(activate, options) {
   var scope = window.angular.element('body').scope();
   scope.$on('$locationChangeSuccess', function(event, next, current) {
     if (next.indexOf('/productPage') != -1) {
       if (!options.isActive) {
         activate();
       }
     }
   });
 }

回调函数 - DOM改变时激活

为了能够在DOM元素变化或者添加到页面中时激活试验,只需要简单地把下方代码添加到激活模式的代码输入框中:

function(activate, options) {
  window.activateOnDOMMutation('#element:not(.changed)', activate, true);
}

函数的第一个参数, #element:not(.changed) ,是想要要监视的DOM元素的选择器字符串。每当该元素出现在页面上或变化时,试验将被激活一次或多次,具体取决于最后一个参数。所有被jQuery支持的选择器都能够使用。如果激活试验之后,版本的代码修改了该元素,将会导致无限循环。为了避免这种情况发生,可以在选择器中添加一个“not(.changed)”来排除版本代码修改的情况,而版本代码修改DOM元素时,都需要加上changed类。

函数的第二个参数, activate 可以用来激活试验。

最后一个参数, 如果设置成 true ,就会在每次DOM元素改变时都会激活一次试验。而如果设置成 false 的话,只会被激活一次。如果向页面中添加了很多内容,却只想在第一次添加内容的时候激活试验,这个参数就会变得非常有用。

Javascript代码示例

/*
 * Condition: Activate when the dom selector changes on the page
 * Type: Callback Function
 *
 * Place the following code in your Project Javascript and call the function below in your experiment's
 * conditional activation code box:
 *
 * window.activateOnDOMMutation('#element', window['eyeofcloud'].push(["activate", EXPERIMENT_ID]), true);
 * @param '#element': DOM Selector of element you'd like to watch
 * @param 'window['eyeofcloud'].push(["activate", EXPERIMENT_ID])': Replace EXPERIMENT_ID with the current
 * experiment's ID
 * @param 'true': True re-activates the experiment on the DOM selector changing or being added to the DOM.
 * False activates the experiment only the first time the selector is added or updated.
 */

(function(win) {
    'use strict';

    var listeners = [],
        doc = win.document,
        MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
        observer;

    function waitForElement(selector, repeat, fn) {

        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn,
            repeat: repeat,
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe($(document), {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        check();
    }

    function check() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
              // Query for elements matching the specified selector
              elements = $(listener.selector);
              for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                 element = elements[j];
                if (!element.ready || listener.repeat) {
                     // Invoke the callback with the element
                      listener.fn.call(element, element);
                  }
             }
        }
    }

    function activateOnDOMMutation(selector, activate, repeat) {
      repeat = repeat === undefined ? false : repeat;
      if (window.MutationObserver || window.WebKitMutationObserver) {
        waitForElement(selector, repeat, function(element) {
           activate();
        });
      } else {
        // this solution does not handle older browsers
      }
    }

    // Expose functions
    win.waitForElement = waitForElement;
    win.activateOnDOMMutation = activateOnDOMMutation;

})(this);

帮助函数

以下是一些帮助函数,在运行更多自定义的优化方案时调用这些函数非常有用。除非另有说明,否则这些代码示例通常用于优化方案JavaScript功能和优化版本JavaScript功能。

此函数从访问者的浏览器读取一个cookie值并返回。

Javascript代码示例

/*
 * Usage
 *    This function will return the value of the cookie name passed in as the argument.
 *
 *  @param {String} name - The name of the cookie.
 */

 var getCookie = function(name) {
   var match = document.cookie.match(name+'=([^;]*)');
   return match ? match[1] : undefined;
 };

此函数设置一个cookie,并接受cookie的名称、值、域和持续时间(以天为单位)作为参数。

Javascript代码示例

/*
 * Usage
 *    This function will set a cookie on the visitor's browser.
 *
 *  @param {String} c_name - The name of the cookie.
 *  @param {String} value - The value of the cookie.
 *  @param {Float} exdays - The number of days the cookie should last.
 *  @param {String} c_domain - The domain on which this cookie should be set and can be read.

 *
 */

 var setCookie = function(c_name,value,exdays,c_domain) {
   c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";";
   var exdate=new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value + ";" + c_domain + "path=/";
 }

元素投票

此功能轮询每隔50ms匹配指定选择器的页面上的元素。当想要在文档准备就绪之后不久将修改未注入到DOM中的元素时,这很有用。

Javascript代码示例

/*
 * Usage
 *    This function is a recursive setTimeout of 50ms that polls for an element matching the selector in the if statement.
 *  @param {String} selector - The CSS path for the selector that you're polling for.
 */

 var pollForElement = function(selector) {
   if ($(selector).length > 0) {
   // code to run once element is found on page
   }
   else {
     setTimeout(pollForElement, 50);
   }
 };

加载外部JavaScript

此函数将附加外部JavaScript到文档的头部。也可以选择提供回调函数。

Javascript代码示例

/*
 * Usage
 *    This function will append an external JavaScript to the head of the document.
 *
 *  @param {String} location - The location of the file you'd like to load.
 *  @param {Function} callback - [OPTIONAL] A function to call when the script has completed downloading.
 *
 */

 var loadScript = function(location, callback){
   var fileRef = document.createElement('script');
   fileRef.setAttribute('type','text/javascript');

   if (callback) {
     if (fileRef.readyState) {  // IE
       fileRef.onreadystatechange = function() {
         if (fileRef.readyState == 'loaded' || fileRef.readyState == 'complete') {
           fileRef.onreadystatechange = null;
           callback();
         }
       };
     } else {  // Non-IE
       fileRef.onload = function(){
         callback();
       };
     }
   }

   fileRef.setAttribute('src', location);
   document.head.appendChild(fileRef);
 };

 loadScript('http://www.example.com/test.js', function() {
   // CALLBACK - code that does something with the data returned by loading the script
 });

获取查询参数值

此函数将返回查询参数的值。如果要在页面本身上呈现查询参数值,这很有用。

例如,可以将访客的搜索内容存储在查询参数中。可以使用此功能在页面上呈现其搜索内容,提供个性化体验。

Javascript代码示例

/*
 * Usage
 *    This function takes a query parameter name and returns its value.
 *
 *  @param {String} name - The name of the query parameter, whose value you want returned.
 */

 var getQueryParam = function(name) {
   var match = window.location.search.match(name + '=([^&]*)');
   return match ? match[1] : undefined;
 }

 // example showing the function called, with the return value inserted in the first h1 element
 $('h1:eq(0)').text(getQueryParam('myParam'));

跟踪动态内容的点击

此用法可跟踪在DOM中作为自定义事件在DOM中准备好的元素上的点击次数。请参阅关于自定义事件目标的文章,了解有关跟踪自定义事件的更多信息。

Javascript代码示例

/*
 *  Usage
 *    Track clicks on elements loaded after DOM ready.  The .delegate() method allows you to select all current and future elements that match the selector passed in as the first argument.
 *
 *  @param {String} selector - Provide the element selector.
 *  @param {String} eventName - Provide the custom event name.
 */

 var selector = [YOUR_SELECTOR];
 var eventName = [YOUR_EVENT_NAME];

 $('html').delegate(selector, 'mousedown touchend', function() {
   window['eyeofcloud'] = window['eyeofcloud'] || [];
   window.eyeofcloud.push(["trackEvent", eventName]);
 });

粘性导航栏

一旦访客滚动网页到元素的原始位置之外,此代码示例将使一个元素的位置固定。

Javascript代码示例

/*
 *  Usage
 *     Pass in the ID of an element whose position you want fixed once the visitor scrolls past the element's initial position.  If the visitor scrolls up again, the element will take on its original position.
 *
 *  @param {String} id - The CSS ID of the element you want to have fixed position.
 *
 */

 var makeSticky = function(id) {
   var menuOffset = document.getElementById(id).offsetTop;
   var docScroll = $(document).scrollTop();
   $(document).bind('ready scroll', function() {
     docScroll = $(document).scrollTop();
     if(docScroll >= menuOffset) {
       $('#'+id).css({'position':'fixed', 'top':'0', 'z-index': '1000'});
     } else {
       $('#'+id).css({'position':'initial','z-index':'0'});
     }
   });
 }

 // Usage example
 makeSticky('mainNavBar');

重定向 - 查询参数

这个代码示例会在URL增加了指定的查询参数后,将访问者重定向到一个新的URL。

请将查询参数排除为受众条件,以防多次添加。

Javascript代码示例


/*
 *  Usage
 *    This JavaScript will add a query parameter you specify to the visitor's current URL.
 *
 *  @param {String} newQuery - Parameter key-value pair. Replace [PARAM_NAME] and [PARAM_VALUE] with your values.
 */

/* _eyeofcloud_redirect=http://custom_add_query_param */
var newQuery = "[PARAM_NAME]=[PARAM_VALUE]";
var _eoc = {redir: document.createElement("a")};
_eoc.redir = {protocol: "https:" == document.location.protocol ? "https://" : "http://",
                domain: window.location.hostname,
                pathname: window.location.pathname
               };
_eoc.cur = window.location.search;
if (_eoc.cur) {
  _eoc.redir.query = _eoc.cur + "&" + newQuery;
} else {
  _eoc.redir.query = "?" + newQuery;
}
_eoc.redir.href = _eoc.redir.protocol + _eoc.redir.domain + _eoc.redir.pathname + _eoc.redir.query;
window.location.replace(_eoc.redir.href);

重定向 - 新路径

此代码示例将会把访客重定向到一个新路径,并保留URL的其余部分。

Javascript代码示例


/*
 *  Usage
 *    This JavaScript will redirect a visitor to a new path.
 *
 *  @param {String} newPath - Replace "/[NEW_PATH]" with your new path, but keep the '/'.
 */

/* _eyeofcloud_redirect=http://custom_new_path */
var newPath = "/[NEW_PATH]";
var _eoc = {redir: document.createElement("a")};
_eoc.redir = {protocol: "https:" == document.location.protocol ? "https://" : "http://",
                domain: window.location.hostname,
                query: window.location.search
               };
_eoc.redir.href = _eoc.redir.protocol + _eoc.redir.domain + newPath + _eoc.redir.query;
window.location.replace(_eoc.redir.href);

重定向 - 相同路径不同域

此代码示例将重定向访客到一个新的域,并保留URL的其余部分。

Javascript代码示例


/*
 *  Usage
 *    This JavaScript will redirect a visitor to the same path on a different domain.  Make sure NOT to include the protocol when passing in the NEW_DOMAIN.
 *
 *  @param {String} newDomain - Change "[NEW_DOMAIN]" to the new domain, NOT including the protocol.
 */

/* _eyeofcloud_redirect=http://custom_new_domain */
var newDomain = "[NEW_DOMAIN]";
var _eoc = {redir: document.createElement("a")};
_eoc.redir.href = window.location.href;
_eoc.redir.hostname = newDomain;
window.location.replace(_eoc.redir.href);

重定向 - 哈希参数

这个代码示例会将访客重定向到一个新的URL,同时保留哈希参数。

Javascript代码示例


/*
 *  Usage
 *    This JavaScript will redirect a visitor to the URL you pass in while preserving all hash parameters.  Be sure to include the protocol in the [REDIRECT_URL]
 *
 *  @param {String} redirectUrl - Replace "[REDIRECT_URL]" with the new URL.
 */

/* _eyeofcloud_redirect=http://custom_keep_hash */
var redirectUrl = "[REDIRECT_URL]";
var _eoc = {redir:document.createElement("a")};
_eoc.redir.href = redirectUrl;  //
_eoc.cur = window.location.search;
if (_eoc.cur) {
  _eoc.redir.search = _eoc.redir.search ? _eoc.cur + "&" + _eoc.redir.search.slice(1) : _eoc.cur;
}
if (window.location.hash) {
  _eoc.redir.hash = window.location.hash;
}
window.location.replace(_eoc.redir.href);

相互排斥

这些代码示例用于优化方案互斥运行。

单页应用

在传统网站上,当访客点击链接时,链接通常会导致一个新的URL并加载一个全新的页面。在单页面应用程序中,整个页面不会重新加载; 相反,某些内容会在当前网址中更改,加载和渲染。由于云眼SDK通常每页加载一次,因此创建了这些代码示例,以帮助适应单页应用程序的行为。

AJAX完成

该代码示例将在AJAX请求完成时应用优化版本代码。在此示例中,要求请求URL包含子字符串“/ shopping-cart”。

Javascript代码示例

/*
 *  Usage
 *     Apply variation code when an AJAX request is completed. In this example, we also require the request URL contain the sub-string "/shopping-cart".
 *
 *  @param {Function} handler - A function to execute when the ajaxComplete event is triggered.
 *
 *  e.g. window.$(document).ajaxComplete(handler)
 */

 // Usage example
 window.$(document).ajaxComplete(function(event, xhr, settings) {
   if (settings.url.indexOf('/shopping-cart') > -1) {
     //apply variation code
   }
 });

集成

可以在集成部分找到使用云眼SDK创建集成的代码示例。

优化版本代码

这些代码示例可以在优化版本代码中使用。

访问页面数据

这是使用Javascript访问在云眼SDK之外定义的对象的示例。请注意,变量必须在云眼SDK之前被声明,确保在执行受众条件匹配检查之前被定义。

Javascript代码示例

/*
 * Example showing how to reference a variable defined natively on the page from inside Eyeofcloud.
 */

 // Variation code example injecting the 'visitorName' property of the 'exampleObject' in the h3 elements
 $('h3').text('Hello,' + window.exampleObject['visitorName']);