我正在制作 Chrome 扩展程序。此扩展的一部分需要能够模拟点击,以便激活页面上的 onClick
事件。这是后台脚本中的代码:
function checkForValidUrl(tabId, changeInfo, tab) {
// If the letter 'g' is found in the tab's URL...
if (tab.url.indexOf('maps') > -1 && tab.url.indexOf('google') > -1) {
// ... show the page action.
chrome.pageAction.show(tabId);
}
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);
chrome.pageAction.onClicked.addListener(function() {
document.getElementById("paneltoggle2").click();
});
这是我从 Chrome 的 JavaScript 调试中得到的错误消息:
Error in event handler for 'pageAction.onClicked': Cannot call method 'click' of null TypeError: Cannot call method 'click' of null
at chrome-extension://deogcaeekneeagffbhdlflichjlodlem/js/main.js:26:42
at chrome.Event.dispatchToListener (event_bindings:387:21)
at chrome.Event.dispatch_ (event_bindings:373:27)
at dispatchArgs (event_bindings:249:22)
at Object.chromeHidden.Event.dispatchEvent (event_bindings:257:7) event_bindings:377
chrome.Event.dispatch_ event_bindings:377
dispatchArgs event_bindings:249
chromeHidden.Event.dispatchEvent event_bindings:257
我猜这与 list 文件中的权限有关...现在我只有“选项卡”的权限。为了模拟点击而不是出错,我是否需要激活其他一些权限?哦,我正在尝试使用第 2 版 list 协议(protocol)来实现这一点。
最佳答案
扩展程序和页面的脚本执行环境不同。
使用chrome.tabs.executeScript
例如,将一些文本粘贴到 Google 搜索字段
文件:manifest.json
{
"name": "My Test",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"page_action": {
"default_icon": "icon.png"
},
"permissions": ["tabs", "http://*/*", "https://*/*"]
}
文件:background.js
function checkForValidUrl(tabId, changeInfo, tab) {
if (tab.url.indexOf("g") > -1) {
chrome.pageAction.show(tabId);
}
}
chrome.tabs.onUpdated.addListener(checkForValidUrl);
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {code: "document.getElementById('gbqfq').value = 'Hello World!';"});
});
在 list 文件中需要主机权限("http://*/*"
)。
但如果问题严格针对 JavaScript 点击事件,请看这里 How to simulate a click with JavaScript?
关于javascript - Chrome 扩展中的模拟点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13319097/