使用chrome.tabs.executeScript(...)时避免多次动态注入同一脚本 [英] Avoid dynamically injecting the same script multiple times when using chrome.tabs.executeScript(...)

查看:492
本文介绍了使用chrome.tabs.executeScript(...)时避免多次动态注入同一脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建Google Chrome扩展程序.基本设置是我有一个浏览器操作按钮,单击该按钮可将jQuery和另一部分JavaScript注入活动选项卡.

I'm building a Google Chrome extension. The basic setup is I have a Browser action button that injects jQuery and another bit of JavaScript into the active tab when it is clicked to do it's thing.

这是我的第一个Chrome扩展程序,但是如果用户再次单击该按钮以执行操作,则脚本将被重新注入.这是一个问题,因为要使用的主要页面都是AJAX,因此页面内容发生了很大变化,但实际页面URL却从未改变.

This is my first Chrome extension, but it seems like if the user clicks the button to take action a second time the scripts will be re-injected. This is a problem because the main pages this is going to work with are all AJAX, so the page content changes significantly but the actual page URL never changes.

这是一个合理的考虑,还是我想得太深,并且有一种简单的方法来防止脚本多次注入同一页面吗?也许我应该将它们指定为内容脚本吗?

Is this a legitimate concern, or am I over thinking it and is there a simple way to prevent the scripts from being injected multiple times into the same page? Should I perhaps be specifying these as content scripts instead?

推荐答案

这绝对是一个合理的问题.

It is absolutely a legitimate concern.

最简单的方法是使用类似于C中#ifndef包含保护的机制.

The easy way would be to use a mechanism similar to #ifndef include guards in C.

定义一个标志,该标志在执行内容脚本后立即置位,并在执行任何操作之前检查它是否已定义.从同一扩展注入的所有脚本都共享JS执行上下文,因此具有全局作用域.

Define a flag that gets set once the content script gets executed, and check if it's defined before doing anything. All scripts injected from the same extension share the JS execution context and therefore global scope.

您的内容脚本可能如下所示:

Your content script might look like this:

if (window.contentScriptInjected !== true) {
    window.contentScriptInjected = true; // global scope

    /* Do your initialization and work */
}

/* global function definitions */

该检查应使用一个显式的true值,以避免在恰巧具有一个具有id属性的元素的页面上出现误报的情况,该元素意外地等于变量名-浏览器创建一个

The check should use an explicit true value to avoid false positives on pages that happen to have an element with id attribute that accidentally equals the variable name - browsers create an implicit global variable that points to that DOM element so for an if check it'll be truthy.

这篇关于使用chrome.tabs.executeScript(...)时避免多次动态注入同一脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆