Simulate clicking elements on the page from a Chrome extension? - javascript

I need to iterate and click all the elements with the class .star_gray on page, and keep the iteration and clicking going after redirection. Running JavaScript code cannot meet the second requirement, so I plan to write a Chrome Extension.
But I failed to simulate clicking events on web pages via the extension. My project is as below:
manifest.json
{
"manifest_version": 2,
"name": "Check'em All",
"description": "",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"persistent": true,
"scripts": ["jquery.js", "background.js"]
},
"content_scripts": [{
"matches": ["file:///*"],
"js" : ["popup.js"]
}],
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
]
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Check'em All!</title>
</head>
<body>
<h1>Check'em All!</h1>
<button id="check-btn">BUTTON</button>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('check-btn');
btn.addEventListener('click', injectScript);
});
function injectScript() {
alert('Handler called!');
chrome.tabs.executeScript(null, { file: 'background.js' });
}
background.js
$(document).ready(function(){
$('.star_gray').click();
$('a.btn.page_next').click();
});
With the code above, when I click the button(#check-btn) on the popup, nothing happens.

You can't get access DOM in background page. And per your code, you might need to learn more from Official Tutorial, since it seems you are confused with "popup", "background" and "content".
Assuming you want to trigger the click event for all elements with class ".star_gray" in the content page, the following code trigger those events once you click on browserAction.
manifest.json
{
"name": "Test",
"version": "1.0",
"permissions": [
"tabs"
],
"description": "Test",
"background": {
"persistent": false,
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"jquery.js",
"content.js"
],
"run_at": "document_end",
"all_frames": true
}
],
"browser_action": {
"title": "Test"
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {command: "click"}, function(response) {
console.log(response.result);
});
});
});
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
$('.star_gray').click();
$('a.btn.page_next').click();
sendResponse({result: "success"});
});

Improving the previous answer by #haibara-ai not to use the tabs permission.
Note that in your case you don't even need to watch for ready() since the script runs only when browser action is triggered which is presumably well after DOMContentLoaded.
manifest.json
{
"name": "Test",
"version": "1.0",
"permissions": [
"activeTab"
],
"description": "Test",
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"title": "Test"
},
"manifest_version": 2
}
background.js
var files = [
'jquery.js',
'content.js',
];
chrome.browserAction.onClicked.addListener(function() {
for (var file of files) {
chrome.tabs.executeScript({
file: file,
allFrames: true,
});
}
});
content.js
$('.star_gray').click();
$('a.btn.page_next').click();
Note, however that this only solves the 'simulate clicking events on web pages via the extension' question. It does not mean that 'keep the iteration and clicking going after redirection' will work. It's best you create another question with the details of what exactly you mean by that.

Related

Chrome Extension - run content script every time new page loads

I am trying to create a chrome extension that injects some content into product pages on a particular site. Currently my content.js only runs if I manually refresh the tab on a matching page. I need it to run automatically every time the user navigates to a matching page.
manifest.json
{
"manifest_version": 2,
"name": "My Test",
"version": "1.0",
"description": "My Test POC",
"icons": {
"128": "/images/128x128_elevated_b_icon_purp.png",
"48": "/images/48x48_elevated_b_icon_purp.png",
"16": "/images/16x16_elevated_b_icon_purp.png"
},
"page_action": {
"default_icon": "/images/16x16_elevated_b_icon_purp.png",
"default_title": "My Test"
},
"background": {
"scripts": ["/scripts/eventPage.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["https://www.tesco.com/groceries/en-GB/products/*"],
"run_at": "document_idle",
"js": ["/scripts/libs/jquery.min.js", "/scripts/content.js"],
"css": ["content.css"]
}
],
"permissions": [
"tabs",
"https://www.tesco.com/groceries/en-GB/products/*"
]
}
eventPage.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request.todo == "showPageAction") {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.pageAction.show(sender.tab.id);
alert('eventPage.js');
});
}
});
content.js
chrome.runtime.sendMessage({todo: "showPageAction"});
alert('content.js');
$(document).ready(function() {
var productName = $('head title').text().replace(' - Tesco Groceries', '');
console.log('Product Name: ' + productName);
//Do stuff
});

Chrome Extension - Background/Event JavaScript Not Responding or Loading

New to making extensions, I origally was attempting to load cookies but realised my EventPage.js didn't seem to be loading - since a basic console.log("Hello") wasn't loading.
I am loading the extension via Chrome "Load unpacked extensions", where manifest,content and background scripts are.
The code attached below is what I've been using to see if I can even get a console log from the event page. Only the content script loads, even If I press a key and that is logged.
CHROME:58
Any suggestions?
Manifest.SON
{
"manifest_version": 2,
"name": "Facebook Extension ",
"version": "1.0",
"description": "",
"permissions": ["storage", "webNavigation", "activeTab", "tabs", "cookies",
"*://*.facebook.com/*"],
"background": [
{
"scripts": ["event_Page.js"],
"persistent" : false
}
],
"content_scripts": [
{
"matches": ["*://*.youtube.com/*"],
"css": ["style.css"],
"js": ["jquery-2.1.0.min.js", "talkToEvent.js"]
}
]
talkToEvent.js
console.log("Hello World!s");
$(document).ready(function() {
console.log("DOM READY!");
$(document.documentElement).keydown(function (e) {
console.log("Key Has Been Pressed!");
chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
;
})
})
});
event_Page.js
console.log("Atleast reached background.js")
chrome.runtime.onMessage.addListener (
function (request, sender, sendResponse) {
console.log("Reached Background.js");
if (request.Message == "getTextFile") {
console.log("Entered IF Block");
$.get("http://localhost:63342/Projects/StackOverflow/ChromeEXT/helloWorld1", function(response) {
console.log(response);
// to send back your response to the current tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
;
});
});
})
}
else {
console.log("Did not receive the response!!!")
}
}
);
You have an incorrect manifest.json.
According event pages docs it should be an object, but in your manifest it is an array.
Correct manifest.json:
{
"manifest_version": 2,
"name": "Facebook Extension ",
"version": "1.0",
"description": "",
"permissions": [
"storage",
"webNavigation",
"activeTab",
"tabs",
"cookies",
"*://*.facebook.com/*"
],
"background": {
"scripts": [
"event_Page.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": [
"*://*.youtube.com/*"
],
"css": [
"style.css"
],
"js": [
"jquery-2.1.0.min.js",
"talkToEvent.js"
]
}
]
}
Also fixed missed comma and close bracket.

Chrome Extension : fill the text fields

My extension should automatically fill my gmail user name and password, but it's not working.
manifest.json
{
"manifest_version": 2,
"name": "Click to execute",
"description": "Akshaya app",
"version": "1.0",
"icons": {
"48": "icon.png"
},
"permissions": [
"tabs", "<all_urls>"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["https://www.facebook.com/*"],
"js": ["popup.js"]
}
]
}
popup. html file
<button id="buttonSet">Set Value</button>
<script type="text/javascript" src="popup.js"></script>
popup.js
function setValue() {
var name ="username";
var pass = "password";
document.getElementById('username').value =name;
document.getElementById('pass').value =pass;
}
document.getElementById('buttonSet').addEventListener('click', setValue);
I got all code from Internet and i haven't any previous experience in working with google extension
and i googled many times for solving the issue i couldn't find any solution for this issue
I hope I understand you right . You could use message passing between your content script to your script that run in popup.html(myscript.js):
manifest.json
{
"manifest_version": 2,
"name": "Click to execute",
"description": "Akshaya app",
"version": "1.0",
"icons": {
"48": "icon.png"
},
"permissions": [
"tabs", "<all_urls>"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["https://www.facebook.com/*"],
"js": ["popup.js"]
}
]
}
popup.html.
<script type="text/javascript" src="myscript.js"></script>
<button id="buttonSet">Set Value</button>
<input type="text" id="username">
<input type="text" id="pass">
popup.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//Take the fields of user and password from the DOM of facebook log-in page
document.getElementById('email').value=request.user;
document.getElementById('pass').value=request.pass;
});
myscript.js
window.onload=function(){
document.getElementById('buttonSet').addEventListener('click',function(){
chrome.tabs.query({}, function(tabs) {
for(var i = 0; i < tabs.length; i++) {
chrome.tabs.sendMessage(tabs[i].id, {user :document.getElementById('username').value,
pass :document.getElementById('pass').value}, function(response) {
});
}
});
});
}
In myscript.js you will need to send a message to a content script tab you want by their ID . Here it's example to that I send to all the tabs message until I find the one that wait for message.
At the end of the result in the first input will show 'username' and you could do this also for the second parameter.
Good luck .

chrome extension - chrome.tabs.executeScript after page redirect

I'm trying to make a Google chrome extension that injects a script upon clicking the extension icon. However, i want the same script to be injected whenever I load/go to another page, without having to click on the extension icon again.
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
if (tab.url.startsWith("https://")){
chrome.tabs.executeScript(tab.id, {
"file": "js/contentscript.js"
}, function () {
console.log("Script Executed .. "); // Notification on Completion
});
}
else{
alert('Error');
}
});
manifest.json i want to execute the script on browserAction so adding the script on content_scripts is not an option i would like to pursue
"permissions": ["tabs", "windows", "notifications", "activeTab"],
"version": "2.0",
"browser_action":
{
"name": "Click to activate extension",
"default_icon": "images/icon.png",
},
"background":
{
"scripts":["js/background.js"]
},
"icons":
{
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
},
"content_scripts":
[{
"js": ["js/jquery-2.1.4.min.js"],
"matches": [ "https://*/*" ],
"run_at": "document_end"
}]
contenscript.js - only a sample script, but gets my point across
alert("here");
setTimeout(function(){window.open("www.google.com");});
P.S. This is my first time asking a question in stackoverflow, please be gentle with me. :D
You could listen to webNavigation.onCompleted event, which fires when a document, including the resources it refers to, is completely loaded and initialized.
Compared with tabs.onUpdated event, you could use event filters to restrict your event notifications. For this part, you could check my answer in this post Running an extension in background on page load/refresh for more details.
manifest.json
{
"name": "36735306",
"version": "1.0",
"description": "Your description here",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"web_accessible_resources": ["content.js"],
"permissions": [
"webNavigation",
"<all_urls>"
]
}
background.js
chrome.webNavigation.onCompleted.addListener(function(details) {
if(details.frameId === 0) {
chrome.tabs.executeScript(details.tabId, {"file": "content.js"});
}
});

Chrome Keyboard shortcuts

I am trying to get a keyboard shortcut to work and at this point I am just testing to see that pressing the shortcut works. So currently what I have it do is send a message to the background page that it is working but the key press never registers. I was wondering how to address this issue.
manifest.json
{
"manifest_version": 2,
"name": "My Cool Extension",
"version": "0.3.1.5",
"description":"User can enter in wepage and press button to open webpage in new tab.",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["jquery-2.1.4.min.js", "content.js"]
}
],
"browser_action": {
"default_icon": "arrow.png",
"default_popup":"popup.html"
},
"permissions": [
"tabs",
"storage"
],
"icons":{
"128":"arrow.png"
},
"commands": {
"openSavedTab": {
"suggested_key": {
"default": "Ctrl+Shift+Y",
"mac": "Command+Shift+Y"
},
"description": "Opens saved tab"
}
}
}
tab_shortcuts.js
chrome.commands.onCommand.addListener(function(command) {
chrome.tabs.update({}, function(tab) {
if (command == 'toggle-pin-tab')
chrome.extension.getBackgroundPage().console.log("Shortcut is functional");
alert("working");
});
});
Thank you wOxxOm for your help. You were right when you said the issue was with a conflicting extension with the same hotkey assigned. Once I disabled the extension my extension worked properly.

Categories

Resources