I am working on a chrome extension that has 2 script files. One is attached to the manifest.json as content_scripts(page script). And I also have a script file attached to my add-on popup.html file(add-on script).
When I declare a var in my page script then I try calling it in my add-on script and I get undeclared varible.
Can can I get communications between the two scripts?
Because if I try doing it all in one then it can not access the elements of the opposite page.
You can easily pass values from background to content script using messaging.
Se below a simple example:
manifest.json
{
"name": "test",
"version": "0.0.1",
"manifest_version": 2,
"description": "Test ",
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_title": "Test "
},
"permissions": [
"*://*/*",
"tabs"
], "content_scripts" : [{
"matches" : ["*://*/*"],
"js" : ["content.js"]
}]
}
background.js
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {data: "some value"});
});
});
content.js
chrome.extension.onMessage.addListener(handleMessage);
function handleMessage(request) {
console.log(request.data);
}
Related
I try to copy some cookies(in text format) to the clipboard. In content_script.js it's not a problem, but when I try to copy something into the clipboard in the background.js it doesn't work because it's not supported. So I decided to send the text from background.js to content_script.js and from there on I can copy it to the clipboard.
I use chrome.tabs.query() and chrome.tabs.sendMessage() to achieve this. Everytime I run my extension I get the following error inside the background console: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
manifest.json:
{
"name": "Cookies to Desktop",
"manifest_version": 3,
"version": "0.0.1",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content_script.js"
]
}
],
"background": {
"service_worker": "background.js"
},
"host_permissions": [
"*://*.google.com/*"
],
"permissions": [
"cookies",
"contextMenus",
"clipboardWrite",
"tabs"
]
}
background.js:
function foo() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id,
{
message: "copyText",
textToCopy: "some text"
}, function (response) { })
})
}
foo()
content_script.js:
chrome.runtime.onMessage.addListener(
function (textToCopy) {
console.log('SUCCESS ' + textToCopy)
alert('SUCCESS')
}
)
How can I successfully send data from background to content
I'm creating a in house chrome extension which collects data from a webpage (broke links etc for SEO) but i'm having issues. My original script injected the js onpage which was great as it had a box and collected what was needed, the only issue was it wasn't a Popup box so it didn't close correctly etc. I now have a script which on load pulls all dom data and a script which display and manipulates the data. The only issue I have is collecting the data from the file.
Manifest.json
{
"name": "",
"version": "1.2.4",
"manifest_version": 2,
"description": "",
"homepage_url": "",
"background": {
"scripts": [
"background.js",
"Returndocdata.js"
],
"persistent": true
},
"browser_action": {
"default_title": ""
},
"icons": { "16": "icon16.png" },
"permissions": [
"https://*/*",
"http://*/*",
"tabs"
],
"content_scripts": [
{
"matches": ["*://*/*"],
"run_at": "document_start",
"js": ["Returndocdata.js"]
}
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab, info) {
chrome.tabs.executeScript({file: 'Returndocdata.js'});
});
chrome.browserAction.onClicked.addListener(function(tab, info) {
chrome.browserAction.setPopup({popup: "inject.html"})
});
inject.html
<div id = "ContactDetails">
<input type="text" name="lname">
</div>
<script src="inject.js"></script>
Returndocdata.js
var all = document.getElementsByTagName("*");
console.log(all);
inject.js
this is the file that needs the returndocdata.js data, i need a way to grab that data and pull it into this keeping the formatting (the htmlcollection)
This works if I include the script in the header but due to it not being ran on the web page itself it only returns data from the popup extension.
It's most likely a small thing
Ta
I'm trying to capture the visible area of a page using chrome.tabs.captureVisibleTab. Here is the code that makes the call:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.name == 'screenshot') {
chrome.tabs.captureVisibleTab(null, null, function(dataUrl) {
sendResponse({ screenshotUrl: dataUrl });
});
}
});
But when I try to capture the tab I get this error:
Unchecked runtime.lastError while running tabs.captureVisibleTab: The 'activeTab' permission is not in effect because this extension has not been in invoked.
Here is my manifest file:
{
"manifest_version": 2,
"name": "Empathy",
"version": "0.1",
"description": "Simulate accessibility issues for websites.",
"browser_action": {
"default_icon": "empathy19.png",
"default_title": "Empathy!"
},
"permissions": [
"activeTab",
"contextMenus",
"desktopCapture",
"tabCapture",
"tts" // Text-to-speech
],
"background": {
"scripts": [
"boot.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"src/helpers.js",
"src/colorblindness.js",
"lib/colorvision.js",
"lib/html2canvas.js"
]
}
]
}
I have active tab permissions
The call is being made from a background script
I'm matching <all_urls>
Why do I get that error?
There are things that talk about <all_urls> as something to match, but what I was missing was the <all_urls> permission. After I added the permission, it worked.
I have a context menu option and when it is selected I want insert some HTML. I have tried doing this
var div=document.createElement("div");
document.body.appendChild(div);
div.innerText='test123';
But it's not working for me.
Note I am trying to avoid using jQuery.
Here you can research how to create an extension and download the sample manifest.json.
Content Scripts can be used to run js/css matching certain urls.
manifest.json
{
"name": "Append Test Text",
"description": "Add test123 to body",
"version": "1.0",
"permissions": [
"activeTab"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content-script.js"]
}
],
"browser_action": {
"default_title": "Append Test Text"
},
"manifest_version": 2
}
content-script.js
var div=document.createElement("div");
document.body.appendChild(div);
div.innerText="test123";
The above will execute the content-script.js for all urls matching http://*/* where * is a wildcard. so basically all http pages.
Content scripts have many properties which can be found in the link above.
Programmatic injection can be used when js/css shouldn't be injected into every page that matches the pattern.
Below shows how to execute the js onclick of the extension icon:-
manifest.json
{
"name": "Append Test Text",
"description": "Add test123 to body",
"version": "1.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Append Test Text"
},
"manifest_version": 1
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: 'var div=document.createElement("div"); document.body.appendChild(div); div.innerText="test123";'
});
});
This uses the executeScript method, which also has an option to call a separate file like so:-
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
file: "insert.js"
});
});
insert.js
var div=document.createElement("div");
document.body.appendChild(div);
div.innerText="test123";
I wanna make an extension that takes the selected text and searches it in google translate
but I can't figure out how to get the selected text.
Here is my manifest.json
{
"manifest_version": 2,
"name": "Saeed Translate",
"version": "1",
"description": "Saeed Translate for Chrome",
"icons": {
"16": "icon.png"
},
"content_scripts": [ {
"all_frames": true,
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
} ],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"background",
"tabs"
]
}
and my background.js file
var text = "http://translate.google.com/#auto/fa/";
function onRequest(request, sender, sendResponse) {
text = "http://translate.google.com/#auto/fa/";
text = text + request.action.toString();
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
chrome.contextMenus.onClicked.addListener(function(tab) {
chrome.tabs.create({url:text});
});
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["selection"]});
and my content_script.js file
var sel = window.getSelection();
var selectedText = sel.toString();
chrome.extension.sendRequest({action: selectedText}, function(response) {
console.log('Start action sent');
});
How do I get the selected text?
You are making it a bit more complicated than it really is. You don't need to use a message between the content script and background page because the contextMenus.create method already can capture selected text. Try adjusting your creations script to something like:
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest});
Then adjust your function to simply get the info.selectionText:
function onRequest(info, tab) {
var selection = info.selectionText;
//do something with the selection
};
Please note if you want to remotely access an external site like google translate you may need to adjust your permissions settings.
I would note - this is no longer valid response if you are moving to manifest version 3. Manifest version 3 adds the concept of "service workers". https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/
You have to update several things, but the basic concept is the same.
manifest.json
"name": "Name of Extension",
"version": "1.0",
"manifest_version": 3,
"description": "Description of Extension",
"permissions": [
"contextMenus",
"tabs",
"activeTab"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
background.js
//Setting up the function to open the new tab
function newTab(info,tab)
{
const { menuItemId } = info
if (menuItemId === 'anyNameWillDo'){
chrome.tabs.create({
url: "http://translate.google.com/#auto/fa/" + info.selectionText.trim()
})}};
//create context menu options. the 'on click' command is no longer valid in manifest version 3
chrome.contextMenus.create({
title: "Title of Option",
id: "anyNameWillDo",
contexts: ["selection"]
});
//This tells the context menu what function to run when the option is selected
chrome.contextMenus.onClicked.addListener(newTab);