【问题标题】:Is it possible to run a script in context of a webpage, before any of the webpage's scripts run, using a chrome extension?是否可以在网页的任何脚本运行之前使用 chrome 扩展程序在网页的上下文中运行脚本?
【发布时间】:2012-11-24 11:11:19
【问题描述】:

我试过"run_at": "document_start",但是当扩展获得控制时没有DOM,所以我不能将script插入head。此外,尝试使用DOMNodeInserted,但不会因为head 而被解雇。如果我尝试在第一个 DOMNodeInserted 事件中插入 script,它将在网页脚本之后执行。

【问题讨论】:

    标签: google-chrome-extension content-script


    【解决方案1】:

    根元素始终存在。您可以将<script> 附加到<html> 元素:

    var s = document.createElement('script');
    s.textContent = 'console.log("Test");';
    document.documentElement.appendChild(s);
    s.parentNode.removeChild(s); // Just to clean-up.
    

    【讨论】:

    • 不保证动态插入脚本标签的执行顺序。所以这个方法可能会在一段时间内失败。
    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多