When I open a new tab, the extension won't activate until I click on it. From that point on I can refresh the tab and the extension will stay active, but deactivates again if I navigate to a different domain. I want it to be always active like some other extensions seem to be. How can I accomplish this? Here is the code:
manifest.json:
{
"name": "Test",
"version": "1.0",
"description": "Test"
"permissions": ["activeTab", "declarativeContent", "storage"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html"
},
"manifest_version": 2
}
background.js:
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
css: ["input[type='password']"]
})],
actions: [
new chrome.declarativeContent.RequestContentScript({
js: ['main.js']
})
]
}]);
});
});
main.js
chrome.storage.sync.get('delay', function(data) {
alert(data.delay || 60);
});
popup.js
<!DOCTYPE html>
<html>
<head>
<style>
input {
width: 80px;
}
button {
outline: none;
}
</style>
</head>
<body>
<input type="number" id="delaySeconds"></input>
<button id="setDelay" type="button">Delay (seconds)</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
let delaySeconds = document.getElementById('delaySeconds');
let setDelay = document.getElementById('setDelay');
let script = ['alert(',')'];
let tab = undefined;
chrome.storage.sync.get('delay', function(data) {
delaySeconds.setAttribute('value', data.delay || 60);
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
tab = tabs[0].id;
});
});
setDelay.onclick = function() {
let delay = {
"delay": delaySeconds.value
};
chrome.storage.sync.set(delay, function() {
chrome.tabs.executeScript(
tab, {
code: script.join(delaySeconds.value)
});
window.close();
});
};
delaySeconds.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
setDelay.click();
}
});
Related
My chrome extension is not saving an string into local storage, can you guys check what i'm doing wrong?
I'm trying to save the data that was copied from the selected text. I can select and show that in the popup but can't save. I want to be able to save so I can have the popup back to it's state when it's open again.
Manifest
{
"manifest_version": 2,
"name": "test ",
"description": "test",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"contextMenus",
"storage"
]
}
Popup html, pretty basic
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="popup.js"></script>
</head>
<body>
<button id="test">Test</button>
<div id="title"></div>
</body>
</html>
Popup js
window.onload = function() {
chrome.storage.local.get('value', function(result) {
document.getElementById("title").innerHTML = result;
});
}
document.addEventListener('DOMContentLoaded', function() {
const test = document.querySelector('#test');
test.addEventListener('click', function() {
chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
chrome.tabs.executeScript(tabs[0].id, { code: `document.getSelection().toString()` }, (result) => {
document.getElementById("title").innerHTML = result;
chrome.storage.local.set({value: result}, function() {
});
});
});
});
});
I will be very grateful to you for your help!
I looked through a lot of similar topics, but these answers did not help me.
I create the expansion for google chrome, and I have to make a click on the icon open a new window with textarea, in this text area I have to write a message and send it to first user on list.
My manifest.json:
{
"name": "Linkedin Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"description": "This extension send message to Likedin users",
"minimum_chrome_version": "26",
"offline_enabled": true,
"icons": {
"16": "img/Spider-16.png",
"48": "img/Spider-48.png",
"128": "img/Spider-128.png" },
"content_scripts": [
{
"js": [
"js/jquery-3.2.0.min.js",
"js/content.js"
],
"matches": [
"https://www.linkedin.com/*",
"<all_urls>"
],
"run_at":
"document_idle",
"all_frames": false
}
],
"background": {
"persistent": false,
"scripts": [
"js/background.js"
]
},
"web_accessible_resources": ["js/main.js", "index.html"],
"permissions": [
"storage",
"<all_urls>",
"tabs",
"activeTab",
"https://www.linkedin.com/*",
"*://*/*",
"notifications"
],
"browser_action": { // broser elements
"default_title": "Linkedin Extension"
},
"externally_connectable": {
"matches": ["https://www.linkedin.com/*"]
}
}
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
// if (tab.url.indexOf('https://www.linkedin.com') == -1) {
// alert('Please go to Linkedin.com, and run this extensions');
// }else{
chrome.tabs.create({
url: chrome.runtime.getURL('index.html'),
active: false
}, function (tab) {
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true,
width: 625,
height: 400,
top: 50
});
});
chrome.tabs.executeScript(null, {file: "js/jquery.js"});
chrome.tabs.executeScript(null, {file: "js/content.js"});
// chrome.tabs.executeScript(null, {file: "js/main.js"});
});
chrome.runtime.onMessage.addListener(function (message_from_content, sender, sendResponse) {
if (message_from_content == 'start'){
chrome.tabs.executeScript(null, {file: "js/main.js"});
console.log(message_from_content);
}
});
content.js
document.getElementById('btnStart').onclick = function () {
var text = document.getElementById('text').value;
// var message = text.replace( '{name}', 'nick');
setTimeout(function () {
chrome.storage.local.set({
'msg': text
});
}, 1000);
};
document.addEventListener('click', function () {
chrome.runtime.sendMessage('start', function (response) {
});
}, false);
main.js
setTimeout(function () {
getData();
}, 1000);
function getData(){
chrome.storage.local.get(['msg'], function (result) {
var text_of_message = result.msg;
//alert(m);
handler(text_of_message);
});
}
var list = $("#results-list").find('.result');
function handler(message) {
$.each(list, function (key, value) {
if (key == 0){
var users_name = $(value).find('.name').find('a').text(); // get name of users
var new_message = message.replace( '{name}', users_name);
$(value).find('.action-trigger').find('li').click(); //get button for open dropdown
$(value).find('.send-message').click(); //click button for send message
$("#subject").val("we are the best IT company in the world");
$("#message-body-content").val(new_message);
}
});
}
I try get some message if button "btnStart" click, and open file main.js, but I get error in console:
Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "chrome-extension://mkeifaecfbamfcillngajldbnaedpepg/index.html". Extension manifest must request permission to access this host.
at chrome-extension://mkeifaecfbamfcillngajldbnaedpepg/js/background.js:33:21
If you now the solution of this problem plese help, and sorry for my English.
I made a very simple Chrome extension where what should happen is the user can enter a value into a text box, press a button, and have the entered value filled into page text box (or any other element).
So, I have
popup.html:
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<script src="popup.js"></script>
</head>
<body>
<textarea type="text" id="data-details" cols="40" rows="5"></textarea>
<input type="button" id="btn-fill" value="Fill" />
</body>
</html>
popup.js:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("btn-fill").addEventListener("click", injectTheScript);
});
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.executeScript(tabs[0].id, { file: "content_script.js" });
});
}
content_script.js:
function fillElements()
{
var dataDetailsStr = document.getElementById("data-details").value;
// error here : Uncaught TypeError: Cannot read property 'value' of null
document.getElementById("txt-page-input").value = dataDetailsStr;
}
fillElements();
manifest.json:
{
"manifest_version": 2,
"name": "Fill Data",
"description": "Fills data on the page",
"version": "1.0",
"permissions": [
"activeTab",
"http://*/*"
],
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html"
},
"content_scripts": [{
"matches": ["http://*/*"],
"js": ["jquery.js", "content_script.js"]
}]
}
document.getElementById ("data-details") always returns null. How to access this element, or how to write this correct? I'm new at this.
The problem is that the document.getElementById("data-details") is in the injected script and the browser search the object that has the id data-details in the page, not in popup.html
So
popup.js
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("btn-fill").addEventListener("click", injectTheScript);
});
function injectTheScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.executeScript(tabs[0].id, { file: "content_script.js" });
chrome.tabs.sendMessage(tabs[0].id, document.getElementById("data-details").value);
});
}
content_script.js
function fillElements()
{
chrome.runtime.onMessage.addListener(function(message) {
document.getElementById("txt-page-input").value = message;
});
}
fillElements();
I'm trying to execute some script inside another external page off of a new tab listener.
background.js
function onCreatedChrome(){
chrome.tabs.onCreated.addListener(function(tab) {
if (tab.url.indexOf("chrome-devtools://") == -1) {
localStorage.setItem("tabid", tab.id);
chrome.tabs.executeScript(tab.id, {code: "alert('Hello World')"}, function() {
if (chrome.runtime.lastError) {
localStorage.setItem("Error", chrome.runtime.lastError.message);
console.error(chrome.runtime.lastError.message);
}
else{
localStorage.setItem("Else case", "This should work")
}
});
}
});
}
function createTab(){
return function(){
var url = "https://www.yahoo.com/";
chrome.tabs.create({ url: url });
}
}
$(document).ready(function(){
onCreatedChrome();
$("#button").click(createTab());
});
manifest.json
{
"manifest_version": 2,
"name": "Execute Script",
"description": "ExecuteScript extension",
"version": "1.0",
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://www.yahoo.com/*"
],
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["jquery.js"]
}
],
"background":{
"scripts": ["background.js",
"jquery.js"]
},
"browser_action": {
"default_popup": "index.html"
}
}
index.html
<html>
<head></head>
<body>
<button id="button">Click Me</button>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="background.js"></script>
</html>
I want thealert('Hello World')to be injected into Yahoo!'s homepage (This is just an example of what I am trying to do in another extension)
The problem with your code is becuase you added jQuery.js after the background.js file
Here is the fix:
"background":{
"scripts": ["jquery.js",
"background.js"]
},
Another alternative for the executeScrit task:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status != 'complete')
return;
if (tab.url.indexOf('yahoo.com') != -1) {
chrome.tabs.executeScript(tabId, {
code: 'alert(1)'
});
}
});
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