Tracking script MauticJS (mtc.js)
Mautic 提供了一种机制,允许插件将自定义 JavaScript 代码注入到 mtc.js 中,该脚本由 PHP 生成,用于管理 Mautic 的跟踪像素和动态 Web 内容。
您可以在第三方网站中嵌入 mtc.js 以管理这些网站与 Mautic 之间的通信。
Note
如需了解如何在您的网站上实现 mtc.js 的基本指南,请访问 Mautic 用户文档。
mtc.js
<?php
namespace Mautic\PageBundle\EventListener;
use Mautic\CoreBundle\CoreEvents;
use Mautic\CoreBundle\Event\BuildJsEvent;
use Mautic\PageBundle\Event\TrackingEvent;
use Mautic\PageBundle\PageEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TrackingSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
CoreEvents::BUILD_MAUTIC_JS => ['onBuildJs', 0],
PageEvents::ON_CONTACT_TRACKED => ['onContactTracked', 0],
];
}
public function onBuildJs(BuildJsEvent $event)
{
$event->appendJs(
<<<JS
document.addEventListener('mauticPageEventDelivered', function(e) {
var detail = e.detail;
if (detail.response && detail.response.events && detail.response.events.tracked) {
console.log(detail.response.events.tracked);
}
});
JS
);
}
public function onContactTracked(TrackingEvent $event)
{
$contact = $event->getContact();
$response = $event->getResponse();
$response->set(
'tracked',
[
'email' => $contact->getEmail()
]
);
}
}
要将自定义 JavaScript 代码注入到 mtc.js 中,请使用一个 事件监听器 来处理 CoreEvents::BUILD_MAUTIC_JS 事件。
该事件接收到一个 Mautic\CoreBundle\Event\BuildJsEvent 对象,可以使用 $event->appendJs($js, $sectionName); 将脚本代码注入其中。
Warning
请注意,触发跟踪调用 Mautic 的代码具有优先级 -255。因此,任何监听此事件的监听器都应使用大于 -255 的优先级。
Warning
仅使用原生 JavaScript 或 <a href=”#mauticjs-api-functions”>MauticJS API 函数</a>,因为 jQuery 和其他库不能保证在第三方网站中可用。
Hooking into the tracking process and returning custom responses
如果需要在请求过程中跟踪联系人,可以通过 /mtc/event 实现,或者向返回给跟踪代码的有效载荷中添加内容,这可以通过通过 CoreEvents::BUILD_MAUTIC_JS 注入的自定义 JavaScript 来实现。请订阅 PageEvents::ON_CONTACT_TRACKED 事件。
监听器可以使用 Mautic\PageBundle\Event\TrackingEvent::set 方法注入自定义有效载荷。
这将使有效载荷暴露给跟踪代码的 mauticPageEventDelivered 事件,位于 detail.response.events 对象中。请参阅 PHP 代码示例。
JavaScript 表单处理钩子
if (typeof MauticFormCallback == 'undefined') {
var MauticFormCallback = {};
}
MauticFormCallback['replaceWithFormName'] = {
onValidateEnd: function (formValid) {
// before Form submit
},
onResponse: function (response) {
// after Form submit
}
};
如果您希望在表单提交之前或之后运行额外的代码,请创建一个 MauticFormCallback 对象。
在示例代码中,将 replaceWithFormName 替换为您的表单名称。
onValidateEnd 和 onResponse 是由 Form.customCallbackHandler 调用操作。
onValidate()
在内置表单验证之前调用。 实现此回调以覆盖内置的表单验证逻辑。
您回调函数的返回值决定了表单的处理方式:
返回
True以跳过内置表单验证,并**继续**进行表单处理。返回
False以跳过内置表单验证,并**阻止**表单提交。返回
null以执行内置表单验证,并让其逻辑决定是否继续进行或阻止表单提交。
返回 True 或 False 会跳过 onValidateStart 的执行。
MauticFormCallback['replaceWithFormName'] = {
onValidate: function () {
// executed before built-in Form validation
var formIsGood = True;
var dontUpdate = False;
if(dontUpdate){
return null;
}else if(formIsGood){
return True;
}else if(!formIsGood){
return False;
}
},
};
onValidateStart()
在默认表单验证的开始时调用,它不接收任何值,并且不需要返回值,也不会处理返回值。
Warning
如果您添加了 onValidate 回调并返回 True 或 False,则不会执行 onValidateStart。
MauticFormCallback['replaceWithFormName'] = {
onValidateStart: function () {
// executed before built-in Form validation
},
};
onValidateEnd(formValid)
Called after all Form validations are complete - either the default validations and/or the onValidate callback - and before submitting the Form.
Receives formValid to determine if the Form is valid.
If this callback returns False then this prevents submitting the Form.
MauticFormCallback['replaceWithFormName'] = {
onValidateEnd: function (formValid) {
// before Form submit
// return False; // prevents submitting the Form
},
};
onErrorMark(callbackData)
Called during error marking. It receives a callbackData object. Return True to skip the default error marking.
var callbackData = {
containerId: containerId,
valid: valid,
validationMessage: callbackValidationMessage
};
MauticFormCallback['replaceWithFormName'] = {
onErrorMark: function (callbackData) {
// called during error marking
},
};
onErrorClear(containerId)
Called to clear an existing error. Receives containerId with the id of the element containing the error. Return True to skip the default error clearing.
MauticFormCallback['replaceWithFormName'] = {
onErrorClear: function (containerId) {
// called to clear an existing error
},
};
onResponse(response)
Called prior to default Form submission response processing. Receives response containing the Form submission response.
Return True to skip the default Form submission response processing.
MauticFormCallback['replaceWithFormName'] = {
onResponse: function (response) {
// called to process the response to the Form submission
},
};
onResponseStart(response)
Called at the beginning of the default Form submission response processing. Receives response containing the Form submission response.
Return value isn’t required and isn’t processed.
Warning
onResponseStart may not get executed if the default response processing gets handled during the onResponse callback
MauticFormCallback['replaceWithFormName'] = {
onResponseStart: function (response) {
// called to process the response to the Form submission
},
};
onResponseEnd(response)
MauticFormCallback['replaceWithFormName'] = {
onResponseEnd: function (response) {
// called to process the response to the Form submission
},
};
Called at the end of the default Form submission response processing. Receives response containing the Form submission response.
Return value isn’t required and isn’t processed.
Warning
onResponseEnd may not get executed if the default response processing gets handled during the onResponse callback
onMessageSet(messageObject)
Called prior to default message insertion. Receives a messageObject containing the message and message type.
Return True to skip the default message insertion.
var messageObject = {
message: message,
type: type
};
MauticFormCallback['replaceWithFormName'] = {
onErrorMark: function (messageObject) {
// called prior to default message insertion
},
};
onShowNextPage()
Called prior to going to the next page in the Form. Useful to adjust the DOM prior to making the page visible.
MauticFormCallback['replaceWithFormName'] = {
onShowNextPage: function (pageNumber) {
// called prior to going to the next page
},
};
onShowPreviousPage()
Called prior to going back to a previous page in the Form. Useful to adjust the DOM prior to making the page visible.
MauticFormCallback['replaceWithFormName'] = {
onShowPreviousPage: function (pageNumber) {
// called prior to going back to previous page
},
};
MauticJS API functions
MauticJS.serialize(object)
This method transforms an object properties into a key=value string, concatenating them with an ampersand.
It’s used when submitting data via MauticJS.makeCORSRequest.
var obj = {firstname: "John", lastname: "Doe"};
var serialized = MauticJS.serialize(obj);
alert(serialized); // Shows "firstname=John&lastname=Doe"
MauticJS.documentReady(functionName|function)
This method validates if the document has finished rendering, then executes the given function. The function argument can be the name of a function or an anonymous function.
- function test() {
alert(‘test’);
}
MauticJS.documentReady(test);
MauticJS.iterateCollection(collection)(functionName|function)
此方法遍历提供的集合,该集合可以是“数组”、“对象”、“HTMLCollection”等。它使用提供的函数参数。 函数参数可以是函数的名称或匿名函数。 该函数接收集合节点和迭代次数作为参数。
var videos = document.getElementsByTagName('video');
// 为所有视频添加自定义数据属性
MauticJS.iterateCollection(videos)(function(node, i) {
node.dataset.customAttribute = 'test';
});
MauticJS.log(arguments)
此方法是 console.log 的一个轻量级包装器。 它的存在是因为某些浏览器不提供此功能。 它接受任意数量的参数,记录它们,然后将这些相同的参数传递给 console.log 方法(如果存在)。
MauticJS.log('Something happened');
MauticJS.createCORSRequest(method, url)
此方法创建一个 XMLHttpRequest,然后检查它是否支持 withCredentials 属性。 如果不支持,则表示用户可能正在使用 Windows 系统,因此它会检查是否存在 XDomainRequest,并在找到时创建它。 最后,它打开并返回 XHR。 您可以使用它来发送包含域 cookie 的跨域请求。 它在 MauticJS.makeCORSRequest 方法中内部使用。
MauticJS.createCORSRequest('GET', 'https://mymautic.com/dwc/slot1');
MauticJS.makeCORSRequest(method, url, data, callbackSuccess, callbackError)
此方法使用 MauticJS.createCORSRequest 打开到指定 URL 的跨域请求,然后分别设置 callbackSuccess 和 callbackError 值。 您可以省略其中任何一个回调函数。 如果省略,则这些回调函数将被替换为基本函数,该函数使用 MauticJS.log(response) 记录来自请求的响应。 回调方法接收服务器响应和 XHR 对象作为参数。 如果响应是 JSON 字符串,它将自动解析为 JSON 对象。 data 参数使用 MauticJS.serialize(data) 进行序列化,然后与请求一起发送到服务器。 所有通过这种方式进行的请求都会设置 X-Requested-With 头为 XMLHttpRequest。
MauticJS.makeCORSRequest('GET', 'https://mymautic.com/dwc/slot1', [], function (response, xhr) {
if (response.success) {
document.getElementById('slot1').innerHTML = response.content;
}
});
MauticJS.parseTextToJSON(maybeJSON)
此方法接收一个文本字符串,并验证其是否为有效的 JSON 字符串。如果是,则将其解析为 JSON 对象并返回。 如果不是,则直接返回传递给它的参数。
var text = '{"firstname": "John", "lastname": "Doe"}';
var json = MauticJS.parseTextToJSON(text);
alert(json); // 将显示 [object Object]
var text = 'not valid json';
var json = MauticJS.parseTextToJSON(text);
alert(json); // 将显示 'not valid json'
MauticJS.insertScript(scriptUrl)
此方法在文档的头部插入一个脚本标签,该脚本标签具有提供的 URL,并且位于其他脚本之前。
MauticJS.insertScript('http://google.com/ga.js');