![](/img/trans.png)
[英]How do I make it so my Chrome extension will only inject a script once?
[英]Chrome Extension: How do I inject a script that the user provided?
我正在为 chrome 进行扩展,用户可以在其中输入脚本,然后按“运行”将其注入当前选项卡。 我正在使用 MV3(清单 v3)。 有没有办法做到这一点?
我的代码:
HTML:
<div class="scriptrunner">
<h1>Script Runner</h1>
<textarea placeholder="Enter script here" id="script"></textarea>
<button id="run">Run Script</button>
</div>
Javascript:
let button = document.getElementById("run");
button.addEventListener("click", async () => {
let input = document.getElementById("script");
let script = input.value;
// this is where the script would be ran
});
我尝试了以下方法:
chrome.scripting.executeScript()
eval()
chrome.scripting.executeScript()
插入带有 function 的脚本标签,然后运行 function我刚开始研究 chrome 扩展,所以也许我错过了一些东西,或者这是不可能的。
ManifestV3 中尚未实现执行任意用户代码(用户脚本)。
同时我们可以在页面上下文中运行这样的代码,即不是作为内容脚本:
async function execInPage(code) {
const [tab] = await chrome.tabs.query({currentWindow: true, active: true});
chrome.scripting.executeScript({
target: {tabId: tab.id},
func: code => {
const el = document.createElement('script');
el.textContent = code;
document.documentElement.appendChild(el);
el.remove();
},
args: [code],
world: 'MAIN',
//injectImmediately: true, // Chrome 102+
});
}
execInPage('console.log(123)');
警告! 如果站点具有严格的Content-Security-Policy
,这可能会被站点阻止,在这种情况下,您可以通过declarativeNetRequest API 删除此 header。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.