上一主题 下一主题
ScriptCat,新一代的脚本管理器脚本站,与全世界分享你的用户脚本油猴脚本开发指南教程目录
返回列表 发新帖

请问怎么将js代码注入iframe当中去

[复制链接]

该用户从未签到

1

主题

0

回帖

3

积分

助理工程师

积分
3
发表于 3 天前 | 显示全部楼层 | 阅读模式
我现在有一段js代码,想要将其注入到某网页的iframe元素中去,但是给我报跨域请求错误,请问有没有大佬知道怎么处理?(变量customCode是我要注入的代码)
  1. const injectToFrames = (frame) => {
  2.         try {
  3.             // 创建脚本元素并注入当前框架
  4.             const script = frame.contentDocument.createElement('script');
  5.             script.textContent = `(${customCode.toString()})();`;
  6.             frame.contentDocument.documentElement.appendChild(script);

  7.             // 递归处理子iframe(穿透多层嵌套)
  8.             const childFrames = frame.contentDocument.querySelectorAll('iframe');
  9.             childFrames.forEach(child => injectToFrames(child));
  10.         } catch (error) {
  11.             console.warn('[跨域框架跳过]', error);
  12.         }
  13.     };

  14.     // 初始注入(从顶层窗口开始)
  15.     injectToFrames(window);

  16.     // 监听动态创建的iframe(MutationObserver方案)[7](@ref)
  17.     new MutationObserver(mutations => {
  18.         mutations.forEach(mutation => {
  19.             mutation.addedNodes.forEach(node => {
  20.                 if (node.tagName === 'IFRAME') {
  21.                     node.addEventListener('load', () => injectToFrames(node));
  22.                 }
  23.             });
  24.         });
  25.     }).observe(document, {
  26.         childList: true,
  27.         subtree: true  // 深度监听所有DOM变化
  28.     });
复制代码
  • TA的每日心情
    无聊
    2025-1-31 20:04
  • 签到天数: 195 天

    [LV.7]常住居民III

    748

    主题

    6546

    回帖

    7218

    积分

    管理员

    非物质文化遗产社会摇传承人

    积分
    7218

    荣誉开发者喜迎中秋油中2周年生态建设者

    发表于 3 天前 | 显示全部楼层
    如果是油猴脚本的话match匹配一下就ok
    混的人。
    ------------------------------------------
    進撃!永遠の帝国の破壊虎---李恒道

    入驻了爱发电https://afdian.com/a/lihengdao666
    回复

    使用道具 举报

    发表回复

    本版积分规则

    快速回复 返回顶部 返回列表