|
我现在有一段js代码,想要将其注入到某网页的iframe元素中去,但是给我报跨域请求错误,请问有没有大佬知道怎么处理?(变量customCode是我要注入的代码)
- const injectToFrames = (frame) => {
- try {
- // 创建脚本元素并注入当前框架
- const script = frame.contentDocument.createElement('script');
- script.textContent = `(${customCode.toString()})();`;
- frame.contentDocument.documentElement.appendChild(script);
- // 递归处理子iframe(穿透多层嵌套)
- const childFrames = frame.contentDocument.querySelectorAll('iframe');
- childFrames.forEach(child => injectToFrames(child));
- } catch (error) {
- console.warn('[跨域框架跳过]', error);
- }
- };
- // 初始注入(从顶层窗口开始)
- injectToFrames(window);
- // 监听动态创建的iframe(MutationObserver方案)[7](@ref)
- new MutationObserver(mutations => {
- mutations.forEach(mutation => {
- mutation.addedNodes.forEach(node => {
- if (node.tagName === 'IFRAME') {
- node.addEventListener('load', () => injectToFrames(node));
- }
- });
- });
- }).observe(document, {
- childList: true,
- subtree: true // 深度监听所有DOM变化
- });
复制代码 |
|