简体   繁体   English

为什么我们需要在从 chrome 扩展注入脚本后删除脚本标签?

[英]Why do we need to remove script tag after injecting script from chrome extension?

Code based on this answer: https://stackoverflow.com/a/9517879/947111基于此答案的代码: https://stackoverflow.com/a/9517879/947111

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

After the script has been loaded, the script tag being removed.加载脚本后,将删除脚本标记。 And indeed if we try to debug target web page, if we will remove this.remove() line, after script was inject there is following line:事实上,如果我们尝试调试目标 web 页面,如果我们将删除this.remove()行,则在注入脚本后会有以下行:

在此处输入图像描述

In every example where I've found injected script is being removed, but my question is why it's necessary?在我发现注入脚本的每个示例中都被删除,但我的问题是为什么它是必要的?

What I want to achieve is to check if this script already was injected and if not inject it.我想要实现的是检查这个脚本是否已经被注入,如果没有注入它。 If remaining script tag is antipattern, how can I check that script already was injected?如果剩余的脚本标签是反模式,我如何检查脚本是否已经被注入?

Hope this can help you, basically, this code is permanently asking for some class or id in DOM, if that element is found you can inject the script into the page context.希望这可以帮助您,基本上,此代码永久要求在 DOM 中提供一些 class 或 id,如果找到该元素,您可以将脚本注入页面上下文。

this use a content script to access the page's context variables and functions:这使用内容脚本来访问页面的上下文变量和函数:

 /**
 * loader.js
 * Injects necessary scripts into page context
 */

// Selector
const BTNPROCESSFILE = 'CB_594922000000710005';        

function injectScript(scriptPath) {
    let s = document.createElement('script');
    s.src = chrome.runtime.getURL(scriptPath);
    s.onload = function() {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
    
}

/**
 * This function checks if any element of the DOM is already rendered or loaded 
 * (You can choose any according to your DOM), 
 * for my case it is an ID called CB_594922000000710005
 */
async function searchElement() {
    do {
        await delayedLog()
        if (BTNPROCESSFILE) {
            //If the element was found then inject the script
            injectScript('src/content-script/injected.js');        
        }
    } while (!BTNPROCESSFILE)
}

function delay () {
    return new Promise(resolve => setTimeout(resolve, 100))
}
  
async function delayedLog () {
    // notice that we can await a function
    // that returns a promise
    await delay()

    btnFileProcess = document.getElementById(BTNPROCESSFILE)
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM