我必须使聊天小部件可移动。该聊天小部件由外部脚本(具体来说,SFDC 嵌入式服务)注入。因此,我无权访问聊天小部件的点击处理程序。
我目前正在使用嵌入式服务的事件处理程序将“mousedown”、“mouseup”和“mousemove”事件侦听器附加到聊天小部件以使其可移动。
虽然小部件可以通过拖动来移动,但在鼠标松开时,也会触发 mouseclick 事件并激活聊天。
考虑到小部件的外部性质,我可以避免触发 mouseclick 事件吗?
如果重要的话我也在使用react。
聊天小部件也通过 salesforce 脚本直接附加到文档正文,因此容器是不可能的。
HTML:
<body>
<script async src='salesforce.com/esw.min.js' /> // external script that adds chat widget
</body>
esw.min.js 的粗略表示:
const chatWidget = <chat-widget />
chatWidget.addEventListener('click', openChat)
document.querySelector('body').append(chatWidget) // adds chat widget into body
我的代码:
const widgetObserver = new MutationObserver((mutations, observer) => {
const helpButton = document.querySelector('chat-widget');
if (helpButton) {
!helpButton.draggable && enableDragging(helpButton);
observer.disconnect();
}
});
function enableDragging(element) {
var displacedX = 0,
displacedY = 0,
currentX = 0,
currentY = 0;
// otherwise, move the DIV from anywhere inside the DIV:
element.onmousedown = dragMouseDown;
element.style.right = currentX + 'px';
element.style.bottom = currentY + 'px';
element.draggable = true;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
currentX = e.clientX;
currentY = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e.preventDefault();
// calculate the new cursor position:
displacedX = currentX - e.clientX;
displacedY = currentY - e.clientY;
currentX = e.clientX;
currentY = e.clientY;
// set the element's new position:
element.style.top = element.offsetTop - displacedY + 'px';
element.style.left = element.offsetLeft - displacedX + 'px';
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
这是我解决这个问题的方法:
我们将使用微前端中的自定义按钮来激活 LiveAgent API,而不是使用 Salesforce 中的默认按钮。
这将按钮的点击处理程序牢牢地置于我们的控制之下,我们将能够使用任何可用的解决方案。