Chrome Extension JS .click(); not working - javascript

So guys let me explain this problem all the code works fine but the .click is not working am trying to make it click on the website button but for some reason its not clicking on it is this a bug or something?
Thank you very much.
CODE:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('status').textContent = "Going To Localhost";
chrome.tabs.query( { active: true, currentWindow: true }, function( tabs ) {
chrome.tabs.update( tabs[0].id, { url: "http://localhost/" } );
});
var button = document.getElementById("mybutton");
button.addEventListener("click", function() {
chrome.tabs.executeScript(null, {code: 'document.getElementById("username").value = "user";'}, function(){
chrome.tabs.executeScript(null, {code: 'document.getElementById("password").value = "pass";'}, function(){
chrome.tabs.executeScript(null, {code: 'var this_button = document.getElementsByClassName("btnLogin"); this_button.click();'}, function(){
});
});
});
}, false);
},function(errorMessage) {
alert(errorMessage);
});

getElementsByClassName (note the pluralization) returns a NodeList. So you'd need to access the first element like:
chrome.tabs.executeScript(null, {code: 'var this_button = document.getElementsByClassName("btnLogin"); this_button[0].click();'});
OR, modern browser that Chrome is, you can use querySelector instead:
chrome.tabs.executeScript(null, {code: 'var this_button = document.querySelector(".btnLogin"); this_button[0].click();'});

Related

Manifest v3 inject script from popup.js

In manifest v2 this code worked and injected the script when button was clicked:
popup.js v2 (works)
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
// Define button on click action
button.onclick = function () {
chrome.tabs.executeScript(null, {
file: 'Scripts/script.js'
});
window.close();
}
});
Now in manifest v3, chrome.tabs.executeScript is replaced with chrome.scripting.executeScript.
scripting permission is added in manifest.json.
popup.js v3 (not working)
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
// Define Scan button on click action
button.onclick = function () {
chrome.scripting.executeScript
(
{
target: { tabId: null}, // ???????
files: ['Scripts/script.js']
}
);
window.close();
}
});
The problem is that chrome.tabs.executeScript requires tabId value as one of the parameters.
How can I get tabId value in popup.js or convert the manifest v2 version javascript so that it works the same?
Thanks to #wOxxOm who posted a link as a comment.
The solution was to get the active tab and use its tabId.
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
button.onclick = injectScript;
});
async function injectScript() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['Scripts/script.js']
});
window.close();
}

(Easy Fix) How to insert div via content.js Google Chrome Extension?

I'm want to create an overlay via content script (content.js) for my google chrome extension. How should I do this?
Here is the code that executes the content script:
chrome.webNavigation.onCommitted.addListener(function() {
chrome.windows.getCurrent(function (currentWindow) {
chrome.tabs.query({ active: true, windowId: currentWindow.id }, function (activeTabs) {
activeTabs.map(function (tab) {
chrome.tabs.executeScript(tab.id, { file: 'contentScript.js', allFrames: false });
});
});
});
}, {url: [{urlMatches : 'https://mail.google.com/'}]});
Here is my contentScript.js
window.addEventListener('DOMContentLoaded', setUpOverlay, false);
function setUpOverlay(){
//Set up overlay div in here
}
The best way to achieve what you want is to use the chrome message api and pass a message to the content script to execute the code
here is how it works:
//popup.js
chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
chrome.tabs.sendMessage(tabs[0].id,'execoverlay',(resp)=>{
console.log(resp.msg)
})
})
//contentScript.js
chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
if(request==='execoverlay'){
// your code goes here
sendMessage({msg:'recieved'})
}
})

onMessage not being executed on Chrome extension

Referencing this post, I am trying to use executeScript or sendMessage to pass a variable to my content.js file. Using Chrome dev tools, I see that it is reaching my content.js file, and it also runs the test alert I insert, but when it gets to the
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
it skips it entirely. I'm not sure what is happening here?
popup.js
function search() {
var name = document.getElementById('txtSearch').value;
chrome.tabs.executeScript({ file: "jquery.js" }, function () {
chrome.tabs.executeScript(null, {
code: 'var name = ' + name + ';'
}, function () {
chrome.tabs.executeScript({ file: 'content.js' });
});
});
}
document.getElementById('btnSearch').addEventListener('click', search);
or popup.js using sendMessage
function search() {
var name = document.getElementById('txtSearch').value;
chrome.tabs.executeScript({ file: "jquery.js" }, function () {
chrome.tabs.executeScript({ file: 'content.js' }, function () {
chrome.tabs.sendMessage({ name: name });
});
});
}
document.getElementById('btnSearch').addEventListener('click', search);
content.js
alert('hi');
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
console.log(message.name);
});
Referencing a different answer I found on SO (cant find it atm), I was missing a function to pass the tab id to the content script.
chrome.tabs.query({ active: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {'type': type, 'name': name });
});

javascript button stops working after close

I have a button that opens a dialog and when I close the dialog it stops working. When I save on the dialog screen it continues to work fine.
This is the button that opens the dialog:
<button class="actionbutton" type="button" onclick="addLitigant();">Add Litigant To Case(s)</button>
The code it calls:
function addLitigant(){
console.log("Calling addLitigant()");
editDialog.extendedDialog('loadUrl','CRFilingLitigantDialog.do?action=addLitigant', 'Add Litigant');
}
The close code on the dialog screen:
param['buttons'].push(
{
id: "closeButton",
text: "(C)lose",
accessKey: "c",
click: function () {
jQuery(this).extendedDialog('close');
jQuery(this).html('');
}
}
);
The save button code:
function () {
console.log("clicking Save");
jQuery('#toAssign option').each(function(){
jQuery(this).attr('selected',true);
});
jQuery('#toUnassign option').each(function(){
jQuery(this).attr('selected',true);
});
editDialog.extendedDialog('postUrl', {url: 'CRFilingLitigantDialog.do?action=updateLitigant', formId: '#crFilingLitigantDialogForm', success: function(){
litigantTabGet('CRFilingLitigantDetail.do', null);
editDialog.extendedDialog ('destroy');
}});
}
We are using jquery 1.6.2. I have tried adding console.log statements to the addLitigant() function but when I come back from the close it doesn't call anything in the console. If I refresh the page it does begin to work again until we close from the dialog.
This is the immediate function that is on the page that opens the dialog
jQuery(function(){
console.log("function");
verificationDialog = jQuery('<div id="verificationDialog"></div>').clerkReviewDialogTemplate({
height:600,
width:800,
title: "Compare Eflex and Icis"
});
compareDialog = jQuery('<div id="comparisonDialog"></div>').clerkReviewDialogTemplate({
height:400,
width:500,
title: "Imported Person"
});
editDialog = jQuery('<div id="editDialog"></div>').clerkReviewDialogTemplate({
height:600,
width:700,
title: "Edit Litigant",
buttons: [
{
id: "save",
text: "S(a)ve",
accessKey: "a",
click: function () {
console.log("clicking Save");
jQuery('#toAssign option').each(function(){
jQuery(this).attr('selected',true);
});
jQuery('#toUnassign option').each(function(){
jQuery(this).attr('selected',true);
});
editDialog.extendedDialog('postUrl', {url: 'CRFilingLitigantDialog.do?action=updateLitigant', formId: '#crFilingLitigantDialogForm', success: function(){
litigantTabGet('CRFilingLitigantDetail.do', null);
editDialog.extendedDialog ('destroy');
}});
}
}
]
});
jQuery('.saveOnChange').bind('change', function(){
updateLitigants();
});
jQuery('.pin').icisAutocomplete({
mustMatch: true,
source: function(request, response){
getQuickAccess(request, response);
},
change: function(event, ui){
updateLitigants();
}}).each(function(index){
var data = jQuery(this).data('staging-json');
jQuery(this).bind('keydown', function(event){
return f5_handler({
event: event,
onf5key: function(){
var popup = people_popup({elem: this, event: event, data: data, success: function(data){
if(data['pin'] != 'null'){
jQuery(event.currentTarget).val(data['pin']);
}
if(data['masterPin'] != 'null'){
jQuery('#'+jQuery(event.currentTarget).attr('masterPinField')).val(data['masterPin']);
}
compareDialog.extendedDialog('close');
updateLitigants();
}});
compareImportedLitigant(data['id'], popup);
}
});
});
});
});
Thanks,
Tom
looks like a post back issue that makes you lose you bind events - this is the only thing that could cause losing button event - try to replace your immediate function with
function pageLoad() {}
see this $(document).ready() and pageLoad() are not the same!
might help
I compared this code to an older version. I noticed that it worked in an older version and I compared the two. The older version had a change in the edit dialog code, I added the close code to it and it now works.
editDialog = jQuery('<div id="editDialog"></div>').clerkReviewDialogTemplate({
height:600,
width:700,
title: "Edit Litigant",
close: function(){
litigantTabGet('CRFilingLitigantDetail.do', null);
editDialog.extendedDialog ('destroy').remove();
},
buttons: [
{
id: "save",
text: "S(a)ve",
accessKey: "a",
click: function () {
jQuery('#toAssign option').each(function(){
jQuery(this).attr('selected',true);
});
jQuery('#toUnassign option').each(function(){
jQuery(this).attr('selected',true);
});
editDialog.extendedDialog('postUrl', {url: 'CRFilingLitigantDialog.do?action=updateLitigant', formId: '#crFilingLitigantDialogForm', success: function(){
litigantTabGet('CRFilingLitigantDetail.do', null);
editDialog.extendedDialog ('destroy');
}});
}
}
]
});

flowplayer: coverImage as data attribute

I'm calling flowplayer like this:
flowplayer("a.rmPlayer", "libs/flowplayer/flowplayer.swf", {
plugins: {
audio: {
url: 'libs/flowplayer/flowplayer.audio.swf'
},
controls: {
volume: true
}
}
});
I'd now like to have different covers for each mp3 file being called. flowplayer provides the coverimage variable (see http://flash.flowplayer.org/plugins/streaming/audio.html), however can I somehow have the images in a data attribute?
I've ended up using the following code, which seems to work flawlessly.
The link:
<a data-toggle="modal" class="rmPlayer" data-fpurl="http://releases.flowplayer.org/data/fake_empire.mp3" data-fpimg="http://releases.flowplayer.org/data/national.jpg">click me</a>
And the corresponding javascript (with '#rmPlayerInterface' being the modal window)
<script type="text/javascript">
$(document).ready(function() {
player = flowplayer("player", "/libs/flowplayer/flowplayer.swf", {
plugins: {audio: {url: '/libs/flowplayer/flowplayer.audio.swf'},controls: {url: '/libs/flowplayer/flowplayer.controls.swf'}},
clip: {autoplay: false, autoBuffering: true}
});
$(document).on("click", ".rmPlayer", function () {
$('#rmPlayerInterface').data('playeroptions', $(this).data());//.music = music;
$('#rmPlayerInterface').modal('show');//:music});//('music', $(this).data('music'));
});
$('#rmPlayerInterface').on('show', function () {
var poptions = $('#rmPlayerInterface').data('playeroptions');
var c = {url: poptions["fpurl"],coverImage: {url: poptions["fpimg"],scaling: 'orig'}};
player.play(c);
});
$('#rmPlayerInterface').on('hide', function () {
player.pause();
});
});
</script>

Categories