【问题标题】:Cannot Manipulate DOM of new tab created via chrome.tabs无法操作通过 chrome.tabs 创建的新选项卡的 DOM
【发布时间】:2016-11-27 16:16:09
【问题描述】:

这是我所做的:

chrome.tabs.create({url:msg.url}, function(tab) {
    chrome.tabs.executeScript(tab.id, {
        runAt:"document_end", 
        allFrames:true,
        code:"var ready = function(fn){ if(typeof fn!== 'function') return ; if(document.readyState === 'complete') {return fn();}  if(document.readyState === 'interactive'){ return fun(); };}; ready(function() { console.log(document.querySelector('#rso h3 a')) alert('yes'); document.querySelector('#rso h3 a').click(); });"

    });
});

但似乎 js 在孤立的环境中运行,所以我无法操作 DOM,有什么解决方法吗?

我还尝试了 code 属性以仅包含以下 sn-p

document.querySelector('#rso h3 a').click();

PS:如果code 属性是,例如对alert() 函数的调用,它就完美无缺。

【问题讨论】:

  • 实际的非工作代码是什么?您是否尝试访问页面设置的变量?此外,该站点可能会动态添加其内容,因此您可能需要 MutationObserver 或 setTimeout。
  • @wOxxOm :编辑帖子并添加代码。代码有额外的部分是为了确保代码在 DOM 准备好之后运行。
  • document.addEventListener('interactive') 是什么?
  • @haibara-ai 查看gomakethings.com/… 的问题
  • @cipher,我猜你的意思是检查document.readyState 是否为interactivedocument,AFAIK 没有 interactive 事件。

标签: javascript google-chrome dom google-chrome-extension


【解决方案1】:

感谢@Xan 和我们对该主题的讨论,通过使用setIntervalclearIntervalcode 属性的组合解决了问题,如下所示:

code: "var intrvl = null; function fn(){ var a = document.querySelector('#rso h3 a'); if(a !== null){ clearInterval(intrvl); a.click(); } }; intrvl = setInterval(fn, 500);"

问题是我试图注入这个 javascript 的特定页面已经创建了我想要动态操作的元素,而document_end 只保证所有静态 DOM 都已加载,我必须这样做解决方法。

另一种方法是在 Javascript 或原始 MutationObserver API 中使用 Mutation Libraries。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多