多次调用内嵌方式二维码扫码登陆window.DTFrameLogin这个函数,导致页面存在多个事件监听器,在查看https://g.alicdn.com/dingding/h5-dingtalk-login/0.21.0/ddlogin.js源码后,我尝试将源码进行修改
window.DTFrameLogin=function(e,t,n,o){
var i,u=e.id&&document.getElementById(e.id)||null,c=document.createElement("iframe");
t.client_id&&t.redirect_uri&&t.response_type&&t.scope?
u?
(
u.innerHTML="",
u.appendChild(c),
c&&c.contentWindow&&c.contentWindow.postMessage&&window.addEventListener?
(
c.src="https://"+((i=t).isPre?"pre-login":"login")+".dingtalk.com/oauth2/auth?iframe=true&redirect_uri="+i.redirect_uri+"&response_type="+i.response_type+"&client_id="+i.client_id+"&scope="+i.scope+(i.prompt?"&prompt="+i.prompt:"")+(i.state?"&state="+i.state:"")+(i.org_type?"&org_type="+i.org_type:"")+(i.corpId?"&corpId="+i.corpId:"")+(i.exclusiveLogin?"&exclusiveLogin="+i.exclusiveLogin:"")+(i.exclusiveCorpId?"&exclusiveCorpId="+i.exclusiveCorpId:""),
c.width=""+(e.width||300),
c.height=""+(e.height||300),
c.frameBorder="0",
c.scrolling="no",
removeEventListener("message", handleMessage), // 移除事件监听器
window.addEventListener("message", handleMessage)
)
:o&&o("Browser not support")
)
:o&&o("Element not found")
:o&&o("Missing parameters");
function handleMessage(e){
var t=e.data,i=e.origin;
if(/login\.dingtalk\.com/.test(i)&&t){
if(t.success&&t.redirectUrl){
var u=t.redirectUrl,c=r(u,"authCode")||"",d=r(u,"state")||"",s=r(u,"error")||"";
c?n&&n({redirectUrl:u,authCode:c,state:d}):o&&o(s)
}
else o&&o(t.errorMsg)
}
}
}
尝试在添加监听器之前移除他,但是经过实践,并无效果,想知道有什么解决办法吗。因为创建的是vue单页面,无法通过刷新页面来进行清除
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
我也遇到了同样的问题,问了我的头头:好像是window.addEventListener 监听iframe 触发多次,换成window.onmessage就行了
确保代码中只有一个地方调用了window.DTFrameLogin,并且传递了正确的回调函数参数。
在调用window.DTFrameLogin时,确保传递了正确的url、width和height等参数。
对代码进行异常处理,确保在出现异常情况时能够正确处理异常,避免回调函数的重复调用。
【 window.DTFrameLogin 重复调用回调函数
】
let hasBeenCalled = false;
function callDTFrameLogin() {
if (!hasBeenCalled) {
// 你的原始代码
window.DTFrameLogin({
// 你的参数
});
hasBeenCalled = true;
}
}
CopyCopy
let callbackFunc;
function callDTFrameLogin() {
if (!callbackFunc) {
callbackFunc = function (res) {
// 你的回调函数代码
};
}
window.DTFrameLogin({
// 你的参数
callback: callbackFunc
});
}
你可以尝试在调用 window.DTFrameLogin 函数之前,先清除掉所有已经存在的 message 事件监听器。可以使用 window.removeEventListener 方法来移除事件监听器,代码如下:
javascript
Copy code
window.removeEventListener("message", handleMessage);
在清除之后,再添加新的事件监听器即可。同时,你也可以考虑在每次调用 window.DTFrameLogin 函数时,重新定义事件监听器,而不是在页面加载时一次性定义。
function handleMessage(e) {
// 处理消息
}
window.DTFrameLogin(function(e, t, n, o) {
// 调用登录函数
window.addEventListener("message", handleMessage);
});
这样做可以确保每次调用 window.DTFrameLogin 函数时,都只有一个有效的事件监听器。