Roll20环境下Chrome扩展中document.querySelector失效问题排查与解决
问题:Chrome扩展无法选中Roll20页面的聊天输入元素
我尝试开发一个简单的Chrome扩展,向Roll20的文本框注入内容,但多种方式选择目标元素均失败,对象始终返回null,哪怕执行:
const foo = document.querySelector('#textchat-input'); alert(foo);
最初尝试的代码
index.html
<div id="test"> <button id="myButton">Press me</button> </div> <script src="libs/jquery-3.4.1.min.js" charset="UTF-8"></script> <script src="script.js"></script>
script.js
document.querySelector("button#myButton").addEventListener("click", postToChat); function postToChat(){ const message = "testing"; const chatInputElement = document.querySelector('#textchat-input textarea'); const chatButtonElement = document.querySelector('#textchat-input .btn'); if (chatInputElement && chatButtonElement) { const activeText = chatInputElement.value; chatInputElement.value = message; chatButtonElement.click(); if (activeText) setTimeout(() => chatInputElement.value = activeText, 10); } }
简化代码定位问题
修改后的script.js:
document.querySelector("button#myButton").addEventListener("click", postToChat); function postToChat(){ const message = "testing"; const chatInputElement = document.querySelector('#textchat-input textarea'); const chatButtonElement = document.querySelector('#textchat-input .btn'); if(chatInputElement==null){alert("chatinputnull");} if(chatButtonElement==null){alert("chatButtonElementnull");} }
执行后两个弹窗均触发,同时控制台出现CSP报错:
Content Security Policy阻止脚本与样式表的内联执行
内容安全策略(CSP)通过阻止脚本和样式表的内联执行来防范跨站脚本攻击。
解决方法:将所有内联脚本(如onclick=[JS代码])和样式移至外部文件。
⚠️ 允许内联执行存在通过注入HTML script元素进行脚本注入的风险。若必须允许,可通过以下方式:
在CSP头中添加unsafe-inline作为源
将内联脚本的哈希值或随机数添加至CSP头。
1条指令
指令 元素 源位置 状态
script-src-elem app.roll20.net/:6 已阻止
了解更多:Content Security Policy - Inline Code
解决方案:修正扩展作用域与加载时机
实际问题为扩展作用域与页面元素加载时机问题,调整后的代码如下:
manifest.json
{ "name": "Charms Check Roll20 Extension", "version": "0.0.1", "description": "A pre-alpha attempt to create a roll20 plugin for Charms Check", "content_scripts": [ { "matches": ["https://app.roll20.net/editor/"], "js": ["script.js"], "run_at": "document_end" } ], "manifest_version": 3, "author": "MrLiioadin" }
script.js
window.setTimeout(test, 5000); // 确保页面完全加载后再执行函数 function test (){ postToChat("Charms Check Extension is ready"); } const postToChat = (msg) => { const chatInputElement = document.querySelector('#textchat-input textarea'), chatButtonElement = document.querySelector('#textchat-input .btn'); if (chatInputElement && chatButtonElement) { const activeText = chatInputElement.value; chatInputElement.value = msg; chatButtonElement.click(); if (activeText) setTimeout(() => chatInputElement.value = activeText, 10); } }
额外操作
删除原有的index.html文件
内容的提问来源于stack exchange,提问作者mrliioadin
相关产品推荐
相关产品推荐

