在酒店booking内,我试图通过使用cjs chrome扩展名注入JavaScript来获取加载页面时以及用户更改日期时的可用客房和价格。我尝试使用$(window).on("load", function)
来等待所有资产加载,但这似乎无法100%地起作用。有时我必须刷新页面几次才能使其正常工作。
这是我目前的代码。使用window.onload
,我将执行功能grabInfo
。
const grabInfo = () => {
const availableData = window._globalTracking;
let availableRooms = [];
availableData.AvailableRooms.map(room => {
let newRoomObj = {
roomCode: room.RoomCode,
rateCode: room.RateCode,
roomName: room.RoomName,
price: room.Price
};
availableRooms.push(newRoomObj);
});
console.log(
`Check-in: ${availableData.ArrivalDtMMDDYYYY} Check-out: ${
availableData.DepartDtMMDDYYYY
}`
);
console.log('Rooms and Rates: ', availableRooms);
};
// when window has loaded everything, perform the following
$(window).on('load', function() {
grabInfo();
// listen for changes to dom (specifically the hotels cards changing to grab new data)
let targetNodes = $('.thumb-cards_products');
let myObserver = new MutationObserver(mutationHandler);
let obsConfig = {
childList: true,
characterData: true,
attributes: true,
subtree: true
};
myObserver.observe(targetNodes[0], obsConfig);
});
我想也许我可以使用$('.thumb-cards_products').on("ready",function())
来等待目标元素的加载,但这似乎不起作用。
虽然window.onready
有效,但是不一致,$('.thumb-cards_products').on("ready",function())
根本无效。最后,我尝试专门从window._globalTracking.AvailableRooms
获取数据,这很可能是从异步api调用返回的。
答案 0 :(得分:1)
尝试设置一个轮询所需内容的时间间隔,一旦可用,您就可以运行功能
function callback() {
if ($('myElement').length) {
clearInterval(token);
grabInfo();
let targetNodes = $('.thumb-cards_products');
let myObserver = new MutationObserver(mutationHandler);
let obsConfig = {
childList: true,
characterData: true,
attributes: true,
subtree: true
};
myObserver.observe(targetNodes[0], obsConfig);
}
const token = window.setInterval(callback, 200);