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

查看:34
本文介绍了避免在使用 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.

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

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 属性的元素,该元素意外地等于变量名称 - 浏览器创建一个隐式全局变量,指向该 DOM 元素,因此对于 if 检查它会是真的.

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天全站免登陆