activate background event using shortcut key - javascript

I am trying to create a chrome extension where if user selects the item in any web page and hit Ctrl+n then that highlighted text spelling should be altered. How do i do it? I have tried using background event page functionality where DOMContentLoaded is used so I can use the listener where there is two task, one is to find the highlighted text and another is listen for the event like Ctrl+n and do the work of reversing the spelling of that highlighted text. However, when I select the text, that selected text is not displayed in console either.
I have tried the following way
{
"manifest_version": 2,
"name": "RevText",
"description": "Reverse the spelling of higlighted text",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "html/popup.html",
"default_title": "click me"
},
"permissions": [
"activeTab",
"storage"
],
"options_page": "html/options.html",
"background": {
"scripts": ["js/eventPage.js"],
"persistent": false
}
}
function init() {
textToHyperLink();
}
function textToHyperLink(event) {
console.log(event);
var text = "";
if (window.getSelection) { // when selecting the text, the highlighted/selected text is not shown in console
text = window.getSelection().toString();
// show the popup with the name of highlighted text
console.log(text);
alert(text);
} else if (document.selection) {
text = document.selection.createRange().text;
}
return text;
}
if(document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded',init);
} else {
init();
}
UPDATE
Tried content_scripts as
{
"background": {
"scripts": ["js/eventPage.js"],
"persistent": false
},
"content_scripts": [
{
"matches" : ["http://*/*", "https://*/*"],
"js" : ["js/content.js"]
}
]
}
}
function init(event) {
console.log('event', event);
alert('event');
}
document.addEventListener('keydown',init);
This way, the console does not log anything neither alert box is opened when I click on the text and hit random keys.

Related

Chrome Extension - Element added to gmail compose page not showing

I'm building a chrome extension and I want to add a content to the div element in the compose window of Gmail web page.
By using the inspect tool in chrome, I got the class of the div, prepend the content but it is not showing.
Manifest.json
{
"manifest_version": 2,
"name": "Gmail Extension",
"description": "Personalised extension for gmail",
"version": "1.0",
"icons": {
"128": "icon128.png",
"48": "icon48.png",
"16": "icon16.png"
},
"content_scripts":[
{
"matches": ["https://mail.google.com/*"],
"js": ["content.js", "jquery-3.3.1.min.js"]
}
],
"permissions": [
"tabs",
"https://mail.google.com/*"
]
}
Content.js
$('div#:ug.J-J5-Ji btx').prepend('<p>Test added</p>');
Image of the compose window, the div highlighted
The text element isn't showing
Thanks
Here's what I did to add a checkbox to the Compose window:
// listen for the event that is fired when the document has finished loading
document.addEventListener('DOMContentLoaded', addUpdateButton, true);
addUpdateButton();
function addUpdateButton() {
var optionsArea = document.getElementsByClassName("aoD az6");
if (optionsArea && optionsArea.length > 0) {
var ecsLabel = document.createElement('label');
ecsLabel.setAttribute('name','ecsslabel');
ecsLabel.innerHTML = "Send as ECS: ";
ecsLabel.setAttribute('id','ecsLabel');
optionsArea[0].appendChild(ecsLabel);
var ecs = document.createElement('input');
ecs.setAttribute('type','checkbox');
ecs.setAttribute('name','ecsbox');
chrome.storage.sync.get("ecs_mode",
function(val) {
ecs.checked = val["ecs_mode"];
});
ecs.setAttribute('id','ecsOption');
optionsArea[0].appendChild(ecs);
}
}
and here's the result (actually, I added several checkboxes, but omitted the code for clarity):

Chrome extension not detecting input field

I'm creating my first Chrome extension and the code just seems to not be working. Basically for now, I want the extension to be able to identify a click on an input field and give an alert. I think the extension is not recognizing the click. I've tried multiple things, but here's the most recent code:
manifest.json
{
"name": "Pi",
"version": "1.0",
"description": "Pi works!",
"permissions": ["activeTab", "declarativeContent", "storage"],
"browser_action": {
"default_icon": {
"32": "pie.png"
}
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}],
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
alert('HELLO WORLD!!');
});
contentScript.js
document.addEventListener('DOMContentLoaded', function(){
document.getElementsByTagName('input').addEventListener("click", function (){
alert("Hi");
});
});
Remove document.addEventListener('DOMContentLoaded', function(){ You actually don't need it. The chrome Browser will decide when to run content script based on run_at settings in the manifest.json default is document_idle. See more here.
GodsArchitect's example is correct for detecting the click event of INPUT tags. However, you may need to consider onFocus event on INPUT tags in case if users use keyboard TAB key to focus into the input field.
const inputTags = Array.from(document.querySelectorAll('input'))
inputTags.forEach(function (input) {
input.addEventListener('focus', function (event) {
alert("Hi...")
}, false)
})
The following does the job.
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
if(target.tagName == 'INPUT'){
alert('You clicked an Input!');
}
}, false);
Source: https://stackoverflow.com/a/9012576/10383955

Google chrome mouseover event

I am new to chrome plugins and I would like to create a mousover event listener where I highlight the hovered element with a extra border or something.
I'll hope someone could help me out.
this is my manifest.json:
{
"manifest_version": 2,
"name": "Custom Google Homepage",
"description":
"This extension shows a Google Image search result for the current page",
"version": "1.0",
"permissions": ["storage"],
"background": {
"scripts": ["background.js"],
"css": ["main.css"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://*/*"],
"css": ["main.css"],
"js": ["core.js"],
"run_at": "document_end",
"all_frames": true
}
],
"page_action": {
"default_popup": "index.html",
"default_title": "My custom google page!"
}
}
Here is my core.js
// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';
// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;
// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
var srcElement = e.srcElement;
console.log(srcElement);
// Lets check if our underlying element is a DIV.
if (srcElement.nodeName == 'DIV') {
// For NPE checking, we check safely. We need to remove the class name
// Since we will be styling the new one after.
if (prevDOM != null) {
prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
}
// Add a visited class name to the element. So we can style it.
srcElement.classList.add(MOUSE_VISITED_CLASSNAME);
// The current element is now the previous. So we can remove the class
// during the next iteration.
prevDOM = srcElement;
}
}, false);
But I don't see the console.log neither and no border can someone help me out with this?

Running a function in chrome extension on double click/select of a word

I am trying to fire a notification whenever I double click on a word/select it. Found several examples online but I still cannot get my example working:
Manifest:
{
"name": "hh",
"description": "hh!",
"manifest_version": 2,
"version": "0.0.0.1",
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "background.js" ],
"all_frames": true,
"run_at": "document_end"
}
],
"permissions": ["storage", "notifications"],
"icons": { "128": "neoprice.png" }
}
background.js
var listener = function(evt) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
displayPrice();
var range = selection.getRangeAt(0);
var text = range.cloneContents().textContent;
console.log(text);
}
};
document.addEventListener('dblclick', listener);
function displayPrice(){
chrome.notifications.create(getNotificationId(), {
title: "message.data.name",
iconUrl: 'hh.png',
type: 'basic',
message: "message.data.prompt"
}, function() {});
}
// Returns a new notification ID used in the notification.
function getNotificationId() {
var id = Math.floor(Math.random() * 9007199254740992) + 1;
return id.toString();
}
I was earlier adding the following but I saw people weren't using it, so I removed it
"app": {
"background": {
"scripts": ["background.js", "assets/jquery.min.js"]
}
},
What I am trying to achieve: Whenever they go to ANY page on selecting a word, it fires the function. Later, I wish to use this for a specific page. :)
Tried: How to keep the eventlistener real time for chrome extensions?
Chrome extension double click on a word
https://github.com/max99x/inline-search-chrome-ext
Both don't really work as I want them too. :(
Solution
It seems you are confused with background page and content script. Your background.js is a content script in fact, though its name is "background". While chrome.notifications api can be only called in background page, trying commenting displayPrice function will make your code work.
Next step
Take a look at above tutorials, wdblclick event triggers, use Message Passing to communicate with background page and call chrome.notications api in background page.
What's more
The following code is used in chrome apps rather than chrome extension.
"app": {
"background": {
"scripts": ["background.js", "assets/jquery.min.js"]
}
},

Trying to get my chrome extension to click a element on page

I am trying to create a chrome extension that can download mp3s from hiphopdx. I have found that once you click the play button on the website it might be possible to extract the download link of the mp3. However I am stuck on getting my extension to click on the play button.
Here is an example of the page on which I am using the extension on:
http://www.hiphopdx.com/index/singles/id.16603/title.fred-the-godson-f-the-kid-daytona-back-to-school-prod-kaimbr
my manifest json
"name": "My Test",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["popup.js"]
},
"browser_action": {
"default_icon": "icon.png"
},
"permissions": ["tabs", "http://*/*", "https://*/*"]
my popup.html
<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
popup.js
function ShowOperationMessage(obj, evt) {
var fireOnThis = obj;
if (document.createEvent) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent(evt, true, false);
fireOnThis.dispatchEvent(evObj);
} else if (document.createEventObject) {
fireOnThis.fireEvent('on' + evt);
}
}
ShowOperationMessage(document.getElementsByClassName("playBtns medium awesome red adjust launchplayer left"),"click");
Modifying your code to content scripts code, i was able to click the button
References
Content Scripts
Background Pages
Browser Action
Added content script section to eliminate background stuff
manifest.json
{
"name": "Mouse Clicks",
"version": "0.0.1",
"manifest_version": 2,
"description": "This demonstrates how mouse clicks are tracked",
"content_scripts": [
{
"matches": ["http://www.hiphopdx.com/index/singles/id.16603/title.fred-the-godson-f-the-kid-daytona-back-to-school-prod-kaimbr"],
"js": ["myscript.js"]
}
]
}
myscript.js
document.getElementsByClassName("playBtns medium awesome red adjust launchplayer left") returns an array so used obj[0] index
function ShowOperationMessage(obj, evt) {
var fireOnThis = obj[0];
if (document.createEvent) {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent(evt, true, false);
fireOnThis.dispatchEvent(evObj);
} else if (document.createEventObject) {
fireOnThis.fireEvent('on' + evt);
}
}
ShowOperationMessage(document.getElementsByClassName("playBtns medium awesome red adjust launchplayer left"), "click");
Let me know if you need more information.

Categories

Resources