/** * 客服云访客 Widget 嵌入脚本 * 用法: */ (function () { if (window.__KEFU_WIDGET_LOADED__) return; window.__KEFU_WIDGET_LOADED__ = true; var script = document.currentScript; if (!script) { var scripts = document.getElementsByTagName('script'); script = scripts[scripts.length - 1]; } var channelKey = (script && script.getAttribute('data-id')) || ''; if (!channelKey) { console.warn('[kefu-widget] missing data-id on script tag'); return; } var src = script && script.src ? script.src : ''; var base = ''; try { var u = new URL(src, window.location.href); base = u.origin; } catch (e) { base = window.location.origin; } var open = false; var iframe = null; var btn = document.createElement('button'); btn.type = 'button'; btn.setAttribute('aria-label', '打开在线客服'); btn.style.cssText = [ 'position:fixed', 'right:24px', 'bottom:24px', 'z-index:2147483000', 'width:56px', 'height:56px', 'border:none', 'border-radius:9999px', 'background:#2563eb', 'color:#fff', 'cursor:pointer', 'box-shadow:0 8px 24px rgba(0,0,0,0.12)', 'display:flex', 'align-items:center', 'justify-content:center', 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif', ].join(';'); btn.innerHTML = ''; var panel = document.createElement('div'); panel.style.cssText = [ 'position:fixed', 'right:24px', 'bottom:24px', 'z-index:2147483001', 'width:400px', 'height:600px', 'max-width:calc(100vw - 32px)', 'max-height:calc(100vh - 32px)', 'border-radius:12px', 'overflow:hidden', 'box-shadow:0 8px 24px rgba(0,0,0,0.12)', 'display:none', 'background:#fff', ].join(';'); function ensureIframe() { if (iframe) return; iframe = document.createElement('iframe'); iframe.title = '在线客服'; iframe.allow = 'clipboard-write'; iframe.style.cssText = 'width:100%;height:100%;border:0;display:block;background:#fff;'; iframe.src = base + '/widget/embed?channel_key=' + encodeURIComponent(channelKey) + '&embedded=1'; panel.appendChild(iframe); } function setOpen(next) { open = next; if (open) { ensureIframe(); panel.style.display = 'block'; btn.style.display = 'none'; } else { panel.style.display = 'none'; btn.style.display = 'flex'; } } btn.addEventListener('click', function () { setOpen(true); }); window.addEventListener('message', function (event) { if (!event || !event.data) return; if (event.data.type === 'kefu-widget-close' || event.data.type === 'kefu-widget-minimize') { setOpen(false); } }); function mount() { document.body.appendChild(btn); document.body.appendChild(panel); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', mount); } else { mount(); } window.KefuWidget = { open: function () { setOpen(true); }, close: function () { setOpen(false); }, channelKey: channelKey, }; })();