【发布时间】:2020-03-28 11:21:03
【问题描述】:
浏览器:谷歌浏览器(Win 10x64)
这是我第一次使用 javascript 的 postMessage API,因此我不了解它的所有细微差别。
我正在尝试遍历一组 DOM 元素,然后在不同的选项卡中打开一堆链接。打开这些选项卡后,在它们各自的 DOM 中找到某些元素,并在主窗口中通过 postMessage() 显示它们。
问题是,即使我打开了几个选项卡,我也只能从最后一个选项卡中获取信息。
这是我的代码:
-
在主窗口准备
postMessage()监听器:window.addEventListener('message', (event) => { console.log(event.data); }, false); -
创建我的 tabs 数组并获取我的 DOM 元素:
alert_list = document.querySelectorAll("tr.expand.alerts-table-tablerow");var newTabs = []; -
循环遍历 DOM 元素,打开选项卡,添加 JS 代码,用所需的数据回调到主窗口。这是主要工作发生的地方:
alert_list.forEach((currentValue, currentIndex) => { alert_status = currentValue.childNodes[13].innerText; if(alert_status == "Enabled") { console.log(currentValue.childNodes[3].innerText + " " + currentValue.childNodes[7].innerText); newTabs.push(window.open(currentValue.childNodes[5].children[0].href, "_blank")); newTabs[newTabs.length - 1].onload = function() { setTimeout(((tab_element) => {return () => { window.parent.postMessage(tab_element.document.querySelectorAll("h1.search-name.section-title.search-title-searchname")[0].innerText); }})(newTabs[newTabs.length - 1]), 120*1000); }; }} );
现在我不断从最后一个打开的标签页中获取信息。准确地说是打开的选项卡的数量。这让我相信问题在于 javascript 对 setTimeout 回调进行了后期绑定,因此我将其更改为以下受 this 启发的内容:
((tab_element) => {return () => {
window.parent.postMessage(tab_element.document.querySelectorAll("h1.search-name.section-title.search-title-searchname")[0].innerText);
}})(newTabs[newTabs.length - 1])
这实际上执行了我想要的实际 DOM 元素的闭包。但是还是不行。
我做错了什么?
如果需要任何其他信息,请告诉我。
谢谢。
【问题讨论】:
-
@Lynx242 那么我如何从最后一个选项卡中获取信息?如果我无法获得信息,我应该也无法从最后一个选项卡中获得信息,对吧?
-
@Lynx242 在 chrome 上试用一下,您可以从已打开的选项卡中读取数据。
-
@Lynx242 这基本上就是我正在做的事情。
标签: javascript closures postmessage