目标-当用户单击特定页面上的 Chrome 扩展程序时,它会自动单击该网站页面上的特定按钮。
我尝试了以下方法来生成自动点击,但没有一个起作用。
我从content-script.js获取background.js中的DOM并运行以下命令(在后台页面中使用这些命令用于其他目的,同样的错误在内容脚本中运行时)。
$(html).find(".button").click();
$(html).find('#button').addEventListener('click', function() { alert("hello"); });
button.addEventListener('click', function() { alert("hello"); });
它要么给我错误,要么不起作用。
第一个命令错误-
jquery.min.js:4 Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
我也尝试将其添加到我的 manifest.json 中,但错误没有变化-
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
请帮助我。谢谢。
最佳答案
您可以在后台脚本中尝试以下代码:
chrome.browserAction.onclicked.addListener(tab => {
chrome.tabs.executeScript(tab, {code:
`var theButton = document.querySelector("button");
if (theButton) theButton.click();`});
});
单击扩展程序的图标 ( browser action ) 时,它将单击事件网页的第一个按钮。如果您需要特定按钮,请在 document.querySelector
调用中优化选择器。
关于javascript - 我想在单击扩展名时自动单击网站上的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47873544/