I am making a Chrome extension. One part of this extension needs to be able to simulate a click in order to activate the onClick
events on the page. Here is the code from the background script:
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(); });
Here is the error message that I am getting from Chrome’s JavaScript debugging:
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
I am guessing that it is something to do with the permissions in the manifest file… Right now I only have permissions to “tabs”. Is there some other permissions I need to activate in order to simulate the click and not get an error? Oh and I am trying to make this capable with version 2 manifest protocol.
Advertisement
Answer
Script execution environments are different for extension and page.
Use chrome.tabs.executeScript
For example, to paste some text to Google search field
File: manifest.json
{ "name": "My Test", "version": "1", "manifest_version": 2, "background": { "scripts": ["background.js"] }, "page_action": { "default_icon": "icon.png" }, "permissions": ["tabs", "http://*/*", "https://*/*"] }
File: 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!';"}); });
In manifest file there is need permission to host ("http://*/*"
).
But if question was strictly on JavaScript click event, look here How to simulate a click with JavaScript?