I am a programming beginner. I would like to develop a simple Chrome extension that allows to bold for dragged content, when I click a button in popup.html. I succeeded to make bold for dragged content, when I click a default icon, but making a button in popup.html with the function required more complex way.
I think that popup.js is necessary to send a message to content.js to trigger the function boldText(). I struggled to use chrome.tabs.sendMessgge or other things to trigger the function, but I failed.
Please give me some advice.
Here is my code:
1. manifest.json
{
"manifest_version": 2,
"name": "test",
"version" : "1.0",
"description": "test",
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"background": {
"scripts": ["jquery-3.3.1.slim.js", "background.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs",
"storage",
"http://*/*",
"https://*/*"
]
}
2. background.js
chrome.browserAction.onClicked.addListener(buttonClicked);
function buttonClicked(tab) {
let msg = {
txt: "hello"
}
chrome.tabs.sendMessage(tab.id, msg);
}
3. content.js
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message, sender, sendResponse) {
if (message.txt === "hello") {
var selection = window.getSelection();
alert(selection);
boldText();
}
}
function boldText() {
document.designMode = "on"; // designMode on for execCommand
document.execCommand('Bold', false);
document.designMode = "off"; // designMode off for execCommand
return false;
}
4. popup.html
<!doctype html>
<html>
<head>
<script src="jquery-3.3.1.slim.js"></script>
<script src="popup.js"></script>
</head>
<body>
<button id="boldButton" value="bold">bold</button>
</body>
</html>
Related
I'm trying to send a message from the background script to the content script and it doesn't work, tried multiple solutions I found but none of them work.
I checked that the background and content scripts both work correctly.
I tried to use chrome.runtime\extention and also with message and request...
hope you could tell me what I'm doing wrong.
manifest:
{
"manifest_version": 2,
"name": "ChangeLang",
"description": "change written text lang",
"version": "1.3",
"permissions": ["storage", "contextMenus", "activeTab", "tabs"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"browser_action": {
"name": "Click to change the icon's color"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["changelang.js"]
}],
"background": {
"scripts": ["background.js"]
}
}
background.js:
chrome.browserAction.onClicked.addListener(function(info, tab) {
alert("click"); // this alert works
chrome.tabs.sendMessage(tab.id, {
"functiontoInvoke": "change"
});
alert("click"); // this alert doesn't works
});
content.js:
function changeLang() {
// do something
}
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
alert("msg"); // never worked
if (message.functiontoInvoke == "change") {
changeLang();
}
});
I think your code setup should look like this:
chrome.browserAction.onClicked.addListener(function(info, tab) {
alert("click"); // this alert works
chrome.tabs.sendMessage(tab.id, {
"functiontoInvoke": "change"
}, function(response) {
response.yourFunc();
});
alert("click"); // this alert doesn't works
});
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
alert("msg"); // never worked
if (message.functiontoInvoke == "change") {
callback({yourFunc: changeLang()});
}
});
I've defined a new content scripts Chrome extension and I would like my extension javascript file to listen on storage changes made by content scripts.
This is manifest.json:
{
"manifest_version": 2,
"name": "my extension",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"storage"
],
"content_scripts": [
{
"matches": ["http://127.0.0.1:8000/*"],
"js": ["jquery.js", "script.js"],
"run_at": "document_end"
}
]
}
This is popup.html:
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
</html>
This is popup.js:
chrome.storage.onChanged.addListener(function(changes, namespace) {
document.body.style.backgroundColor = "green";
});
This is script.js:
chrome.storage.local.set({'key': 'value'}, function(){});
chrome.storage.local.set({'key': 'other_value'}, function(){}); // modify a key value to trigger the event
I would like to have my extension html (popup.html) updated when values are updated in storage by the content script (script.js).
I'm not sure if this is possible or perhaps the correct way to communicate in this case is window.postMessage.
I am working on chrome extension and I've stuck on a very specific part where backgroundjs is suppose to send a message to current active tab .
This is my manifest file
manifest.json
{
"manifest_version": 2,
"name": "test",
"description": "Some_Test",
"version": "1.0",
"background": {
"page": "background.html"
},
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "content.js" ]
}
],
"permissions": [
"background",
"activeTab",
"tabs",
"http://*/*",
"https://*/*"
],
"browser_action": {
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<button id="read-button">Read</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
function readObject(e) {
console.log(chrome.extension.getBackgroundPage().read());
}
document.getElementById('read-button').addEventListener('click', readObject);
background.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="background.js"></script>
</body>
</html>
background.js
function read() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
return response.farewell;
});
});
}
content.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log("hello");
if (request.greeting == "hello")
sendResponse({ farewell: "goodbye" });
});
This is where the error is :
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
return response.farewell;
});
It seems that I cannot access tabs[0] object or I am unable to understand the Array which it returns, because i want to access the active tab and tabs[0] simply means it is getting the first tab in the browser and not the active tab.
I think this can only happen if the active window is the Developer Tools of the background page.
Just switch to a normal browser window when testing the extension or define read() function in popup.js and remove the background page altogether if it's not absolutely needed.
Can someone please tell me why the following extension does not work? I tried to replace the inline script with script src=" ..." /script and it still doesn't work. Is it better to list both javascripts in content scripts or remove them both?
POPUP.html
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
<script>
function pasteSelection() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
}
</script>
</head>
<body>
<textarea id="text"> </textarea>
<button onclick="pasteSelection(); ">Paste Selection</button>
</body>
</html>
selection.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"chrome://favicon/",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["selection.js", "paste.js"]
"run_at": "document_start",
"all_frames": true
}
]
}
You can't use any inline code and you are using several depreciated methods. Not moving all of the inline code to an external file is probably what is causing the problem, but it is not good to use depreciated methods anyway. Fixing it would make it look like this:
Popup.html
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="text"> </textarea>
<button id="pasteButton">Paste Selection</button>
</body>
</html>
Popup.js
window.onload = function() {
var pasteButton = document.getElementById("pasteButton");
pasteButton.onclick = function(){
chrome.tabs.query({active:true,currentWindow:true}, function(tab) {
chrome.tabs.sendMessage(tab[0].id,{method:"getSelection"},function(response){
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
};
};
selection.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
Manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"manifest_version": 2,
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"chrome://favicon/",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["selection.js", "paste.js"],
"run_at": "document_start",
"all_frames": true
}]
}
I would like to make a chrome extension that use a popup to do :
select text
click on the chrome extension icon
get it in the popup (textarea, ...)
This question was already asked here but Google did updates and the code I found is not working anymore ...
selection.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
popup.html
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
<script>
function pasteSelection() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
}
function getSelectedText(){
if (window.getSelection){
var str = window.getSelection();
}else if (document.getSelection){
var str = document.getSelection();
}else {
var str = document.selection.createRange().text;
}
return str;
}
function affichage(){
var sel = getSelectedText();
alert(sel);
}
function addtext() {
document.form.champ.value = getSelectedText();
}
</script>
</head>
<body>
<form>
<textarea id="text"></textarea>
<button onclick="pasteSelection(); " type="submit">get text</button>
</form>
</body>
</html>
manifest.json
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"options_page": "page_options.html",
"browser_action": {
"default_title": "Selected Text",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"chrome://favicon/",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["selection.js"],
"run_at": "document_start",
"all_frames": true
}
],
"manifest_version": 2
}
I thank you in advance for your help :)
There are multiple problems in your script
chrome.extension.onRequest is deprecated in favor of chrome.extension.onMessage
chrome.tabs.sendRequest is deprecated in favor of chrome.tabs.sendMessage
CSP will not allow inline scripting and <script> tag in html code.
window object of Content Script is different from normal page window object.
After applying multiple changes to code i got it working
manifest.json
Eliminated not applicable sections of manifest
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"browser_action": {
"default_title": "Selected Text",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["selection.js"],
"run_at": "document_start",
"all_frames": true
}
],
"manifest_version": 2
}
popup.html
Ensured popup.html adheres to CSP
<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 300px;
}
textarea {
width: 250px;
height: 100px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="text"></textarea>
<button id="submit">get text</button>
</body>
</html>
popup.js
Script to pick current tab and send message and update DOM.
function pasteSelection() {
//Select current tab to send message
chrome.tabs.query({
"active": true,
"currentWindow": true,
"status": "complete",
"windowType": "normal"
}, function (tabs) {
//It returns array so looping over tabs result
for (tab in tabs) {
//Send Message to a tab
chrome.tabs.sendMessage(tabs[tab].id, {
method: "getSelection"
});
}
});
}
//Adding a handler when message is recieved from content scripts
chrome.extension.onMessage.addListener(function (response, sender) {
//Set text to text area
var text = document.getElementById('text');
text.value = response.data;
});
// Bind On click event to pasteSelection() function
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("submit").onclick = pasteSelection;
});
selection.js
Passes selected text to popup.html
//Add a handler to handle message sent from popup.html
chrome.extension.onMessage.addListener(function (request, sender) {
//Hanlde request based on method
if (request.method == "getSelection")
//Send selected text back to popup.html
chrome.extension.sendMessage({
data: document.getSelection().toString()
});
else chrome.extension.sendMessage({}); // snub them.
});
References
tabs.query()
tabs.sendMessage()
extension.onMessage()
extension.sendMessage()
CSP