我正在为 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()
插入带有函数的脚本标签,然后运行该函数我刚刚开始研究 chrome 扩展,所以也许我错过了一些东西,或者这是不可能的。
Developer mode
,这可能会出现问题,因为它全局允许所有已安装扩展程序使用此危险权限。示例:
https://stackoverflow.com/a/77579988
通过主世界的个人解决方法
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 删除此标头,但这会降低网站的安全性,并且如果您无条件地执行此操作,即您应该添加一个用户将显式启用的选项(默认情况下禁用)。