Chrome Extensions - Click on element in actual page [duplicate] - javascript

This question already has answers here:
How to access the webpage DOM/HTML from an extension popup or background script?
(2 answers)
Closed 6 years ago.
I'm trying to make a simple extension, that can click in a element on the my principal page, example: I have a login page that have 6 buttons to choose a password and I want to simulate a click in each button(I already did this on Selenium).
But, when I use de DOM(document object) the chrome is getting the document from a new HTML and is not getting my HTML.
Above my example:
background.js
function checkForValidUrl(tabId, changeInfo, tab) {
chrome.pageAction.show(tabId);
}
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
chrome.tabs.onUpdated.addListener(checkForValidUrl);
chrome.pageAction.onClicked.addListener(function(tab) {
var element = getElementByXpath("//label[contains(text(),'1')]");
element.click();
});
On my code, when I try to select a Element I can't get the main page.
MANIFEST.js
{
// Required
"manifest_version": 2,
"name": "Minha Extensão",
"version": "2",
// Recommended
"description": "A plain text description",
"icons": { "16": "icon-w-1.png",
"48": "icon-w-2.png",
"128": "icon-w-3.png" },
"background": {
"scripts": ["background.js"]
},
"page_action": {
"default_icon": "icon-w-3.png"
},
"permissions": ["tabs", "http://*/*", "https://*/*"]
}
My next step will be, in the moment that I click on the extension button, open a new window with buttons that when I click, can simulate a click on another button in the main page.

You can't access web page DOM from background page. You have to insert content script.
See more in - Chrome documentation

Related

Using chrome manifest 3, Im trying to simulate the keypress of (Command+Option+i) [duplicate]

This question already has answers here:
Programmatically trigger keyboard shortcuts, e.g. in Gmail
(1 answer)
Keyboard simulation using a chrome extension
(1 answer)
Closed 11 months ago.
I am trying to create my first chrome extension that opens up the dev tool via icon click of the extension.
I am trying to simulate the keypress normally required to open the dev tools in chorme mac(Command+Option+i), I tried to first just simulate the ( Enter ) key to test if the code works meaning when I click the chrome extension ICON it simulates the enter key being pressed, but no luck
attached are my 3 files that make the extension.. manifest.js ,background.js content-script.js
Manifest.js
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": [ "activeTab", "scripting","storage"],
"action": {
"default_title":"Click to open dev tools",
"default_icon": {
"16": "/images/i.png",
"32": "/images/i.png",
"48": "/images/i.png",
"128": "/images/i.png"
}
},
"icons": {
"16": "/images/i.png",
"32": "/images/i.png",
"48": "/images/i.png",
"128": "/images/i.png"
}
}
background.js
//// background.js ////
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content-script.js']
});
});
Content-script.js
//// content-script.js ////
// document.body.style.backgroundColor = '#6C8CA8';
let keyEvent = new KeyboardEvent('keypresc', {key: 'Enter'});
document.window.dispatchEvent(keyEvent);
// alert( "key pressed");
I tried to first get the script injection working when I click the icon to execute the content-script.js after some time and trial It managed to work. I used changed background color to experiment with that.
Next, I tried to create a keyevent that simulates pressing the "Enter" key I would go to the URL bar and type a website hover over it and press click the icon that should've simulated the enter key but did not work.
I added an alert to make sure that the javascript was executing and it showed me that it is, but my actual code to simulate "enter" is wrong.

chrome.browserAction.onClicked fires when I load a new page

I am developing a very simple extension for Google Chrome which sets a badge text when the user presses the browser action icon. Here is the background.js:
chrome.browserAction.onClicked.addListener(function() {
chrome.browserAction.setBadgeText({text: "Ko"});});
When I load the extension for the first time in chrome://extensions there's no problem and works properly, but if I close and open the browser and then I go to a webpage the Badge text appears automatically even when I have not pressed the browser action icon as you can see in the image:
This is my manifest.json:
{
"name": "Hello Extensions",
"description": "Base level extension",
"version": "1.0",
"manifest_version": 2,
"browser_action": {
"default_icon": "check-circle-green-512.png"
},
"background": {
"scripts":["background.js"]
},
"permissions": ["storage", "alarms", "notifications"]
}
Thanks for the help and greetings.
The browserAction button is common for all opened tabs and windows. When you set/change the badge text using setBadgeText this effect displayed on all tabs in all chrome windows. If you want a separate badge text for each window you will need to manage it at your own. See a simple example below that changes the badge text on tab onActivated event:
chrome.tabs.onActivated.addListener(function(activeInfo) {
console.log(activeInfo.tabId);
chrome.browserAction.setBadgeText({text: "T"+activeInfo.tabId});
});

Chrome extension: context menu icon not showing

I am building a Chrome extension and I set up a context menu which will show up and check the items (images or text) that the user selects from a table in the extension's popup.
This is my code for creating the context menu in popup.js's window.onload:
chrome.contextMenus.removeAll();
chrome.contextMenus.create( {title: "Toggle Selected",
documentUrlPatterns: [ "chrome-extension://*/popup.html"],
contexts:["selection"], onclick: toggleselected} );
This is the function that gets called on the context menu's onclick - also in popup.js (simplified version):
function toggleselected(info, tab)
{
var selection = window.getSelection(),
q0 = document.querySelectorAll("[id^='id0']"),
q1 = document.querySelectorAll("[id^='id1']");
for (var i = 0; i < somearray.length; i++)
{
if (selection.containsNode(q1[i], true))
{
somearray[i].checked = !somearray[i].checked;
q0[i].checked = !q0[i].checked;
}
}
updatesomearrayinfo();
}
And this is my manifest.json file (again, simplified version):
{
"manifest_version": 2,
"name": "Extension Name",
"version": "1.0",
"description": "Random description",
"browser_action":
{
"default_icon":
{
"16": "icon16.png",
"32": "icon32.png",
"48": "icon48.png",
"128": "icon128.png"
},
"default_popup": "popup.html"
},
"background":
{
"scripts": ["somescript.js"],
"persistent": true
},
"permissions": ["contextMenus", "tabs", "downloads", "<all_urls>"]
}
Everything works fine and the context menu correctly shows up when needed ... except that it doesn't have the extension's own icon next to it, but the default Chrome extension icon (the grey one). What can be done to correct this behavior? The icons in my manifest are ok, one of them (the 16x16 pixels, I believe) is correctly shown on my extension button, and apart from others usually doing the whole context menu thing from event pages, using chrome.runtime.onInstalled, contextMenus.onClicked.addListener and other listeners (which I am reluctant to use, since I specifically need to work with the variables from popup.js - e.g. somearray and queries on popup's elements), I don't seem to be doing anything different than things done by other extensions or the code samples in the answers here on StackOverflow. And they all get their own extension icons shown, apparently without doing anything special.
EDIT: Also, does anyone knows why the context menu for a selection is triggered only when the selection contains more than one specific item (an image, in my case)?

Making my browser action act as an on/off switch (with appropriate icons)

I'm working on a Google Chrome extension, and I essentially want the browser action to act as an on/off switch. Whenever it is "on", it will have a certain icon and the script is executed on the page. Whenever it is "off", it has a certain icon and the script is not executed.
Here's my manifest.json:
{
"manifest_version": 2,
"name": "Resource Control",
"description": "Controls what resources load from a website.",
"version": "1.0",
"icons": {
"16": "locked_16.png",
"48": "locked_48.png",
"128": "locked_128.png"
},
"browser_action": {
"default_icon": "locked_16_off.png" //icon is "off" by default
},
"background": {
"scripts": ["main.js"]
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
}
And here's main.js:
var toggled = false;
chrome.browserAction.onClicked.addListener(function(tab) {
toggled = !toggled;
if(toggled){
chrome.browserAction.setIcon({path: "locked_16_on.png", tabId:tab.id});
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
}
else{
chrome.browserAction.setIcon({path: "locked_16_off.png", tabId:tab.id});
chrome.tabs.executeScript(tab.id, {code:"alert()"});
}
});
if (toggled) {
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
}
Right now I'm just working on getting this functionality working before moving on, so to test I'm just setting the page's background to red. However, whenever I load a new webpage, the icon is reverted back to the "off" icon even though the extension is still "on", and the script isn't injected into the new page. Can someone help me find where I'm going wrong?
When you pass a tabId to chrome.browserAction.setIcon it only sets the icon for when that specific tab is active. If you switch to a different tab, the icon will revert to the default.
You are only running chrome.tabs.executeScript when the browserAction is clicked on. If want code injected on every page you either need to use a content script that is injected on all tabs or listen for new tabs getting created and executeScript every time.

Chrome Extension: Open tab, go to url, fill form and submit form

I am following a tutorial here
http://www.blackweb20.com/2010/01/11/creating-your-own-google-chrome-extension/
I can open fine a tab with a custom extension and load a url, and I would like to fill and submit a form with javascript on the page opened. For example, could I submit a search on google.com?
Here is what I have so far:
manifest.json
{
"name": "My First Extension",
"version": "1.0",
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"background_page": "background.html",
"permissions": [
"tabs"
]
}
background.html
<script>
// get tab http://stackoverflow.com/questions/1979583/how-can-i-get-the-url-for-a-google-chrome-tab
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': "http://google.com"}, function(tab) {
// Tab opened. Wait until page loads, from here it is not working
jQuery(document).ready(function() {
jQuery('#tsf').submit();
});
});
});
</script>
Your jQuery code is getting executed in the background page not the new tab. Try using chrome.tabs.executeScript to execute the submit in the tab environment.
While you could do this using the chrome extension, I would suggest you to look into Selenium Browser Automation
It will also help you do the same in multiple browser instead of just chrome.

Categories