仅用纯JavaScript无API实现获取Facebook最新帖子URL的问题咨询
解决方案
以下三种方案按优先级从高到低尝试:
方案1:直接从元素属性提取真实URL
Facebook 不会把帖子URL完全做动态加载,绝大多数场景下URL已经存在于a标签的内置属性中,无需触发事件:
let a = document.getElementsByClassName("oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8 b1v8xokw")[0]; // 先遍历data自定义属性查找包含posts路径的URL for (let attr of a.attributes) { if (attr.name.startsWith('data-') && attr.value.includes('/posts/')) { console.log('真实帖子URL:', attr.value); break; } } // 若data属性未找到,查找React框架挂载的内部属性 for (let prop in a) { if (prop.startsWith('__reactProps')) { const reactProps = a[prop]; // 优先查props下的href字段 if (reactProps?.href && reactProps.href !== 'https://www.facebook.com/#') { console.log('真实帖子URL:', reactProps.href); break; } // 兼容href存放在子元素props的场景 if (reactProps?.children?.props?.href) { console.log('真实帖子URL:', reactProps.children.props.href); break; } } }
方案2:正确模拟悬停事件触发URL填充
之前模拟事件失败的原因是Facebook使用PointerEvent而非普通mouseover,且会校验事件的可信标记和坐标参数,完整触发代码如下:
let a = document.getElementsByClassName("oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8 b1v8xokw")[0]; const rect = a.getBoundingClientRect(); // 触发FB优先监听的pointerover事件 a.dispatchEvent(new PointerEvent('pointerover', { bubbles: true, cancelable: true, isTrusted: true, clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 })); // 补充触发mouseover兼容旧逻辑 a.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true, isTrusted: true })); // 等待100ms异步更新href属性后取值 setTimeout(() => { console.log('真实帖子URL:', a.href); }, 100);
方案3:手动拼接帖子URL
Facebook 公开的个人主页帖子URL格式为 https://www.facebook.com/{主页ID}/posts/{帖子ID},你可以从最新帖子的父元素属性中提取帖子ID直接拼接:
// 找到最新帖子的根元素,类名包含x1yztbdb的为帖子容器 const postEl = document.querySelector('[class*="x1yztbdb"]'); // 提取data-ft属性中的帖子ID const ftData = JSON.parse(postEl.getAttribute('data-ft')); const postId = ftData.mf_story_key?.split(':').pop(); const pageId = ftData.content_owner_id; // 拼接最终URL const postUrl = `https://www.facebook.com/${pageId}/posts/${postId}`; console.log('真实帖子URL:', postUrl);
内容的提问来源于stack exchange,提问作者user2401856
相关产品推荐
相关产品推荐

