Open chrome extension's popup window on event - google-chrome

trying to build a chrome extension that allows you to highlight text, do right click and on click send that text to extension's browser popup and open it.
chrome.contextMenus.create({
title: "send text to popup",
contexts:["selection"],
onclick: function(info, tab) {
//console.log(info.selectionText);
sendtopopup(info.selectionText);
}
});
function sendtopopup(text) {
console.log(text);
chrome.runtime.sendMessage({result: text}, console.log("runtime is executed on background"));
} // end send pop up
<!DOCTYPE html>
<html>
<head>
<style>
/* Add styles for the popup here */
</style>
</head>
<body>
<h4>below should be hihglighted text</h4>
<p id="result"></p>
<p id="result2"></p>
</body>
<script>
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
document.getElementById("result").innerHTML = request.result;
document.getElementById("result2").innerHTML = "sameple text to check listener";
}
);
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
document.getElementById("result").innerHTML = request.result;
document.getElementById("result2").innerHTML = "2222222sameple text to check listener";
}
);
</script>
</html>
this is the manifest.json file code:
{
"manifest_version": 2,
"name": "send text to popup",
"version": "1.0",
"description": "Sends highlighted text to popup",
"permissions": [
"activeTab",
"contextMenus"
],
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_popup": "popup.html"
}
}
is there a way that right click function execution the extension's popup window would open from browser extension icon?

At the moment, there isn't a way to have the popup open when a context menu item is clicked. In Manifest V3, a new API is available in Chrome Canary (action.openPopup) which would allow this: https://bugs.chromium.org/p/chromium/issues/detail?id=1245093
I wrote a blog post about the status of this API across browsers and some of the work that is being done to make the behaviour consistent: https://oliverdunk.com/2022/11/13/extensions-open-popup
I'm hopeful we'll take the API to stable soon to make this possible.

Chrome has openPopup api.
chrome.action.openPopup(
options?: OpenPopupOptions,
callback?: function,
);
OpenPopupOptions :windowId
Read more at chrome.action

Related

I want to link a google chrome extension popup button action with the content of the page

I'm just having a hard day trying to figure out this but still couldn't get anywhere, I have a google chrome extension built with manifest v3 which is the latest version supported by google, Inside this extension i have a popup html file that opens up when you click on the extension icon
What i want is, when i click the "change background" button the background of the active tab/page changes to red
What i tried is doing it without the popup thing and it worked! when you click on the icon it actually changes the background color of the active page here is the code for the files used:
manifest.json
{
"name": "Action script injection demo",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_title": "Click to show an alert",
"default_popup": "./popup.html"
},
"permissions": ["activeTab", "scripting"],
"background": {
"service_worker": "background.js"
}
}
popup.html
<html>
<header>
</header>
<body>
<input type="button" value="Change background" id="btnChangeBackground" />
</body>
</html>
background.js
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: {tabId: tab.id},
files: ['content.js']
});
});
content.js
document.querySelector("body").style = "background-color:red;";
Thank you in advance.

How to build a toggle on/off chrome extension

I'm completely new in building chrome extensions. I've tried a building a couple extensions that work when i click on them. This time i've been trying to figure out how to build a toggle on/off extensions.
Basically what i'm trying to build is an extension that executes a code (ex: alert('Hi')) when i toggle it on and off and will continue to run on every page until i toggle it off.
I've looked a lot and I can't find any good resources that could explain how to do it.
i have my manifest and my html file and i know i need a popup.js and background.js files but i have no idea what to put inside.
manifest.json
{
"manifest_version": 2,
"name": "Toggle Extension",
"description": "My Personal Toggle Extension",
"version": "1.0.0",
"icons": {
"128": "img/icon_128.png"
},
"browser_action": {
"default icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["js/background.js"]
}
}
popup.html
<html lang="en">
<head>
<meta charset="utf-8">
<title>POC Extension</title>
<meta name="description" content="POC Extension">
<meta name="author" content="Yann Bohbot">
<!-- <link rel="stylesheet" href="css/popup.css"> -->
<link rel="stylesheet" href="css/popup.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/popup.js"></script>
</head>
<body>
<h2>Toggle</h2>
<ul class="tg-list">
<li class="tg-list-item">
<h4>Flat</h4>
<input type="checkbox" id="cb4" class="tgl tgl-flat" value = "Disable" />
<label class="tgl-btn" for="cb4"></label>
</li>
</ul>
</body>
</html>
an extension that executes a code (ex: alert('Hi')) when i toggle it
on and off and will continue to run on every page until i toggle it
off.
Seems like you have to read a lot on this resourse: google extension guide
I would have done this task in this way:
popup.html have popup.js file, which have a function which sends
state of your extension ("ON" or "OFF") to background script;
content.js runs on each tab in browser, and it starts with request
to background script whether your extension is ON or OFF;
background script sends a respond to each content script with
current state of your ext.
when content script get the respond,
it checks it and decides shoud it stop or continue execution of your
script.
So, it is obvious that at first you need a content script. Put this snippet in you manifest file:
"content_scripts": [
{
"js": [ "content.js" ],
"matches": [ "<all_urls>" ],
"all_frames": true,
"run_at": "document_end"
}
],
At the beginning of your content.js file write:
console.log("Hello, Yann!");
chrome.runtime.sendMessage( {myQuestion: "Is it ON or OFF?"}, function(response) {
console.log( "Extension state is: " + response.state); // should be ON
if(response.state !== "ON") return;
// Put the code you want to execute on every tab below:
// ....
});
Your background.js file must have this piece of code:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log( "Your question was: " + request.myQuestion );
// here we will get information whether ext is ON or OFF from the popup;
sendResponse({state: "I don't know, but I'll find it out!"});
});
Try this, if it works, I'll try to help with popup.

my chrome extension popup opens after a few seconds, it's slow compared to other extensions

When we click on the extension button, listed beside the address bar (where the URL appears), popup.html of the corresponding extension shows up. (of course, according to manifest.json)
When I click on lastPass, the popup appears instantly, but when I click on my custom-extension (contains nothing but popup.html), the mouse icon changes to loading for 1-2 seconds & then the popup opens up.
Did some digging on why my popup is so slow, the google-groups had something like
window.load=setTimeout(activate,0);
Unable to find any related documentation, or working sample.
Please help in figuring out why my extension popup is so slow, though the code contains nothing just the popup (beginner in chrome-extensions development).
Update
manifest.json
{
"manifest_version": 2,
"name": "Sample Name",
"description": "Sample Descriptoin",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"<all_urls>"
]
}
popup.html
<!doctype html>
<html>
<head>
</head>
<body>
<div>
<label>Enter HR Password</label>
<input type='password' id='passwd'/>
<button id='evaluateResults'>Evaluate</button>
<ul id='results' style='width:100px;'>
</ul>
</div>
<script src='popup.js'></script>
</body>
</html>
popup.js
var totalCorrect=0, totalWrong=0;
document.getElementById('evaluateResults').addEventListener('click',function(){
var passwd=document.getElementById('passwd').value;
if(passwd==='123'){
var strCode="var scriptOptions = {role:'blank'};";
chrome.tabs.executeScript(null, {code: strCode,allFrames:true}, function(){
chrome.tabs.executeScript(null, {file: "content_script_evaluate.js",allFrames:true});
});
}else{
alert("Incorrect Password");
}
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request);
var ul=document.getElementById('results');
var li=document.createElement('li');
li.innerHTML=request.testName+" - "+(request.testResult?"Correct":"Wrong");
ul.appendChild(li);
});
What worked for was to add an empty background page.
This is not explained in the Google Documentation (or at least I did not find it), so it was more of a fluke, but seems to work.
The idea is that the plugin is loaded once when you come to the page (so before you even click), as opposed to being reloaded over and over again on each click.
In the manifest add something like:
{
//...
"background": {
"page": "bg.html"
}
//...
}
And the bg.html can just be an empty HTML file:
<html>
</html>
Again - never found an explicit link or resource explaining why this should be done like this, and I am not sure it is the best practice, but it did work for me.

Communication between ContentScript.js and Chrome Extension

I simply want to send the current tab url to my extension:
Following is my manifest.json
{
"name": "DocUrlExtention",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["contentscript.js"]
}
]}
Following is my contentscript.js
chrome.extension.sendRequest({url: window.location.href}, function(response) {
console.log(response.farewell);
});
Following is my popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<script>
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
});
</script>
<!-- JavaScript and HTML must be in separate files for security. -->
<!--<script src="popup.js"></script>-->
</head>
<body>
<div id="mydiv">Doc Id:</div>
</body>
</html>
I don't see anything in console. I am new to Chrome extensions.
Your manifest file contains "manifest_version": 2,, which enables the Content Security Policy. By default, Inline JavaScript will not be executed. And, there is no way to relax the CSP such that inline JavaScript is allowed.
You've got two options:
Remove "manifest_version": 2 (which disabled the default CSP).
Move the inline JavaScript to an external file.
The second method is recommended, and also suggested in your code...
...
<!-- JavaScript and HTML must be in separate files for security. -->
<!--<script src="popup.js"></script>-->
</head>
...
PS. The Dev tools for the pop-up can be opened by right-clicking on the browser action icon, and selecting the last option, "Inspect popup".

Chrome extension - start point

Where I can find an example code of chrome extension which shows the current address in a popup?
Thanks.
Ron
Documentation: http://code.google.com/chrome/extensions/getstarted.html
Samples: http://code.google.com/chrome/extensions/samples.html
This is the official documentation and sample code for Google Chrome extensions. In your manifest you want to declare a popup for either a page or browser action (whichever best suites your extension). In your popup HTML file you probably want something like the following;
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function initPopup() {
chrome.tabs.getSelected(null, function (tab) {
document.body.appendChild(document.createTextNode(tab.url));
});
}
</script>
</head>
<body onload="initPopup();"></body>
</html>
This very simply appends the URL of the selected tab to the body of the popup.
Your manifest should look like the following;
{
"name": "My First Extension",
"version": "1.0",
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs"
]
}
The file structure for this example is a single folder containing manifest.json, popup.html and icon.png.
On the Extensions page (chrome://extensions) you should click Load unpacked extension... and navigate to this folder. If you make any changes to the manifest be sure to click the Reload link to pick up these changes.
I hope this helps but I strongly suggest reading through the documentation I mentioned above to get a better understanding of what you're doing.
EDIT: Added missing null argument to code and included an example manifest and file structure based on additional information gathered from comments.
Try this code in your popup, it works for me (Google Chrome 14-beta):
chrome.windows.getCurrent(function(window) {
chrome.tabs.getSelected(window.id, function(tab) {
console.log(tab);
console.log(tab.url); // url of the current tab
});
});
For more information check: http://code.google.com/chrome/extensions/tabs.html#method-getSelected
It looks like all these answers are outdated so here is a manifest 2 example. You will need jQuery for this example. I have included all the files in a gist.
manifest.json
{
"manifest_version": 2,
"name": "Hello World",
"version": "1.0",
"author": "Christian Juth",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Hello World</title>
<script src="jquery.js"></script>
<script src="popup.js"></script>
</head>
<body>
<span id="address"></span>
</body>
</html>
popup.js
$(document).ready(function(){
//define query
var query = { active: true, currentWindow: true };
//query tabs
chrome.tabs.query(query, function (tabs) {
currentAddress = tabs[0].url;
$('#address').text(currentAddress);
});
});