I'm trying to made a options site for my Chrome Extension. I want just that if checkbox 1 is enable script is runs etc...
I searched around but I found only outdated threads for this topic.
This is the manifest.json from my extension:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"options_page": "options.html",
"description": "The first extension that I made.",
"content_scripts": [
{
"matches": ["http://*.example.com/*"],
"all_frames": true,
"js": ["script1.js", "script2.js"]
}
],
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"tabs", "http://*.example.com/*"
]
}
The options.html:
<!DOCTYPE html>
<html>
<body class="uber-frame" i18n-values=".style.fontFamily:fontfamily;.style.fontSize:fontsize" style="font-family: 'Segoe UI', Tahoma, sans-serif; font-size: 125%">
<div id="main-content" align="center">
<div id="mainview">
<section id="scripts">
<h3>Scripts</h3>
<label>
<input type="checkbox" class=script1 >
<span>Enable Script 1</span>
</label>
<div>
<label>
<input type="checkbox" class=script2>
<span>Enable Script 2</span>
</label>
</div>
</section>
</div>
</div>
</body></html>
I don' t know how can i say the extension wich script shout be activ and which not.
I think I need a other script to get the values from the classes of the checkboxes and
probably I should set the content scripts to backgrond scripts.
Would be great if someone could help me.
Update: I've updated all codes for make both script run at the same time.
OK, at first you should save options data in localstorage, so you can access data from all pages. that makes your job easy.
For manipulating data I've created a javascript file named as global.js.
This file must be included at the start of options.html and content.js manually or in manifest.json.
global.js
var localStoragePrefix = "myextension_";
var LS_options = localStoragePrefix + "options";
var Options = {
Scripts : [
{
name : "script 1",
path : "script1.js",
enable : false
},
{
name : "script 2",
path : "script2.js",
enable : false
}
]
};
function DB_setValue(name, value, callback) {
var obj = {};
obj[name] = value;
console.log("ayarlar kaydedildi");
console.log(obj);
chrome.storage.local.set(obj, function() {
if(callback) callback();
});
}
function DB_load(callback) {
chrome.storage.local.get(LS_options, function(r) {
if ($.isEmptyObject(r[LS_options])) {
DB_setValue(LS_options, Options, callback);
} else {
Options = r[LS_options];
callback();
}
});
}
function DB_save(callback) {
DB_setValue(LS_options, Options, function() {
if(callback) callback();
});
}
function DB_clear(callback) {
chrome.storage.local.remove(LS_options, function() {
if(callback) callback();
});
}
And here is the updated options.html, you will see some js files included.
jquery.min.js (You don't need to use this, I just want to make it more useful)
global.js
options.js
options.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="globals.js"></script>
<script type="text/javascript" src="options.js"></script>
</head>
<body class="uber-frame" i18n-values=".style.fontFamily:fontfamily;.style.fontSize:fontsize" style="font-family: 'Segoe UI', Tahoma, sans-serif; font-size: 125%">
<div id="main-content" align="center">
<div id="mainview">
<section id="scripts">
<h3>Scripts</h3>
<div id="scriptTemplate" style="display:none">
<label>
<input type="checkbox" data-script = "script.js" />
<span>Enable Script</span>
</label>
</div>
</section>
</div>
</div>
</body>
</html>
Event handler attachments are in options.js file.
options.js
$(function(){
DB_load(startOptionsPage);
});
function startOptionsPage() {
$.each(Options.Scripts, function(index, script) {
var $scriptTemplate = $("#scriptTemplate").clone().show();
$scriptTemplate.find("label span").html("Enable " + script.name);
$scriptTemplate.find("label input[type='checkbox']")
.data("script", script.path)
.click(function() {
if ($(this).is(":checked")) {
script.enable = true;
} else {
script.enable = false;
}
DB_save(function() {
console.log("DB saved");
});
})
.prop('checked', script.enable);
$("#scripts").append($scriptTemplate);
});
}
And in content.js file we are getting Options and including the script if there is a selected one.
content.js
DB_load(function() {
$.each(Options.Scripts, function(index, script) {
if (script.enable) {
$.getScript(chrome.extension.getURL(script.path), function() {
console.log(script.name + " was loaded!");
});
}
});
});
script1.js
alert("Hello from script1");
script2.js
alert("Hello from script2");
For all of this you should update the manifest.json file.
including global.js into the content_script
permission for localstorage
including web_accessible_resources for script1.js and script2.js (Why?)
Finally here is the updated manifest.json
manifest.json
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"options_page": "options.html",
"description": "The first extension that I made.",
"content_scripts": [
{
"matches": ["http://stackoverflow.com/*"],
"all_frames": true,
"js": ["jquery.min.js","globals.js","content.js"],
"run_at": "document_end"
}
],
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"tabs", "http://stackoverflow.com/*", "storage"
],
"web_accessible_resources": [
"script1.js",
"script2.js"
]
}
Your script folder should be like this,
How can I add more scripts?
There are only two changes you must make,
You will add script to main folder like the other script1.js and script2.js, and also you will add it to web_accessible_resources into the manifest.json.
You will also update "global.js", just add new script object to Options.Scripts array. like this.
var Options = {
Scripts : [
{
name : "script 1",
path : "script1.js",
enable : false
},
{
name : "script 2",
path : "script2.js",
enable : false
},
{
name : "script 3",
path : "script3.js",
enable : false
}
]
};
That's all. But don't forget to remove extension from chrome before you load the new updated one, because old options will stay there, and that won't work as you expect if don't do that.
Related
Hello there,
I want to remove thumbnail images that appear on YouTube. I am using the following code for this.
while (true) {
$("ytd-thumbnail").remove()
}
When I paste this code into console, all thumbnail images are removed. I want it to work on the backplane by adding an extension. The code for the plug-in I'm preparing is below.
manifest.json;
{
"manifest_version": 2,
"name": "test",
"description": "test extension",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>TEST</title>
<script src="popup.js"></script>
</head>
<body>
<h1>TEST</h1>
<button id="checkPage">Check !</button>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
while (true) {
$("ytd-thumbnail").remove()
}
});
}, false);
}, false);
When I press the checkPage button nothing happens. But this code works when I add a console. What is the problem? Thanks in advance.
There are several issues with the extension :
You are trying to use $ i.e. jquery which is not available in your
popup.js
You are trying to access "ytd-thumbnail" dom elements which belong
to youtube page and not your popup.html. So, even if you replace $
with document.querySelector , you won't find those elements.
I created a working version that looks something like this. I have not included popup.html which is same as yours.
manifest.json
{
"manifest_version": 2,
"name": "Hello Extensions",
"description" : "Base Level Extension",
"version": "1.0",
"browser_action": {
"default_icon": "hello_extensions.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["background.js"],
"all_frames" : true
}
],
"permissions": [
"activeTab",
"tabs"
]
}
2.popup.js
document.addEventListener('DOMContentLoaded', function()
{
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function()
{
chrome.tabs.query({"active":true}, function (tabs){
chrome.tabs.sendMessage(tabs[0].id, "removeThumbnails", function (response) {
});
});
});
});
When the button is clicked, retrieve the active tab and send it a "removeThumbnails" message.
3.background.js
chrome.runtime.onMessage.addListener(function(message, callback) {
if (message == "removeThumbnails")
{
var elements = document.querySelectorAll("ytd-thumbnail");
elements.forEach(a => a.parentNode.removeChild(a));
}
});
background.js is content script and runs in youtube page. It can now access all the dom elements in youtube page. When we receive a "removeThumbnails" message , get all ytd-thumbnail elements and remove them from page.
I need to build a chrome extension that manipulates dom
I am following some tutorial and now
I have this manifest.json:
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/"
]
}
This is my popup.html:
<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key with
value "popup.html".
-->
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
font-size: 100%;
}
#status {
/* avoid an excessively wide status text */
white-space: pre;
text-overflow: ellipsis;
overflow: hidden;
max-width: 400px;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script src="popup.js"></script>
<script type="text/javascript">console.log('attempt #0 to console log something');</script>
</head>
<body>
<div id="status"></div>
<img id="image-result" hidden>
</body>
</html>
And this is my popup.js:
document.addEventListener('DOMContentLoaded', function() {
console.log('attempt #3');
});
chrome.tabs.onUpdated.addListener(
function ( tabId, changeInfo, tab )
{
if ( changeInfo.status === "complete" )
{
chrome.tabs.executeScript({ code: "console.log('attempt #4');" }, function() {
console.log("console.log(attempt #5)");
});
}
});
As you can see I tried various ways to console log something after page loaded but none of them work
what do I do?
So I think that the simple solution is just to create a content script and there to wait until the page is load :
manifest.json
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"content_scripts": [
{
//Set your address you want the extension will work in mataches!!!
"matches": ["http://mail.google.com/*", "https://mail.google.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}
],
"permissions": ["activeTab", "https://ajax.googleapis.com/"],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
content.js
window.onload=function(){
console.log("page load!");
}
You could also use with message passing between background.js and your content page and to check that tab is loaded but for your case I think it's enough.
This is how I do:
manifest.json
...
"background": {
"scripts": [
"assets/js/background.js"
],
"persistent": false
},
....
background.js
function openOrFocusOptionsPage() {
var optionsUrl = chrome.extension.getURL('popup.html');
chrome.tabs.query({}, function(extensionTabs) {
var found = false;
for(var i=0; i < extensionTabs.length; i++) {
if(optionsUrl == extensionTabs[i].url) {
found = true;
chrome.tabs.update(extensionTabs[i].id, {"selected": true});
}
}
if(found == false) {
chrome.tabs.create({url: "popup.html"});
}
});
}
chrome.extension.onConnect.addListener(function(port) {
var tab = port.sender.tab;
port.onMessage.addListener(function(info) {
var max_length = 1024;
if(info.selection.length > max_length)
info.selection = info.selection.substring(0, max_length);
openOrFocusOptionsPage();
});
});
chrome.browserAction.onClicked.addListener(function(tab) {
openOrFocusOptionsPage();
});
Not a duplicate of Executing Chrome extension onclick instead of page load because I need to execute script on a button press in popup.html, not when the user presses the icon.
This is my first chrome extension and I've got my content.js working the way it should on page load, but I only want to execute it after the user pushes a button in popup.html. I know you can specify run_at in manifest.json, but this doesn't work because I want it to only run when the user clicks a button (not the icon), and I'm using pageAction so I need the icon to be grayed out on urls which don't contain the letter 'g', hence the specification in my background.js. I think I must be missing something regarding the communication between background.js and content.js, but I'm feeling very lost so if anyone can explain what I'm missing that would be great.
Here is my manifest.json:
{
"manifest_version": 2,
"name": "my extension",
"description": "it doesnt work",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"declarativeContent"
],
"page_action": {
"default_popup": "popup.html"
},
"icons" : { "16": "16.png",
"48": "48.png",
"128": "128.png" },
"content_scripts": [
{
"js": ["content.js"],
"matches": ["<all_urls>"],
"run_at": "document_end"
}
]
}
Background.js:
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'g' },
})
],
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
}); ]
}
]);
});
});
Content.js:
document.addEventListener("DOMSubtreeModified", function(event){
if(document.getElementsByClassName(".class")) {
var x = document.querySelectorAll(".class");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.visibility = "hidden";
} }
});
popup.html:
<html>
<head>
<script type="text/javascript" src="content.js"></script>
</head>
<body>
<p>Turn off <span>class, "class"</span></p>
<button type="button">Turn off</button>
</body>
</html>
This will run if you are on the selected tab. You may need to change how you select that tab though. Basically this will will send a request to the tab and the tab listens for these requests. If you get the proper greeting, you can do your function.
popup.html
<html>
<head>
<script type="text/javascript" src="content.js"></script>
</head>
<body>
<p>Turn off <span>class, "class"</span></p>
<button type="button" id="button">Turn off</button>
</body>
</html>
background.js
$('#button').on('click',function()
{
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
});
});
content.js
if(document.getElementsByClassName(".class")) {
var x = document.querySelectorAll(".class");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.visibility = "hidden";
}
}
Also, as #Makyen had suggested, remove content scripts from your manifest so it isn't always being injected into every tab. I edited my answer as well per this suggestion.
I can't get a response from my content script to show up in my popup.html. When this code runs and the find button is clicked, "Hello from response!" prints, but the variable response is printed as undefined. The ultimate goal is to get the current tab's DOM into my script file so that I can parse through it. I'm using a single time message to a content script to get the DOM, but it's not being returned and is showing up as undefined. I'm looking for any help possible. Thanks.
popup.html:
<!DOCTYPE html>
<html>
<body>
<head>
<script src="script.js"></script>
</head>
<form >
Find: <input id="find" type="text"> </input>
</form>
<button id="find_button"> Find </button>
</body>
</html>
manifest.json:
{
"name": "Enhanced Find",
"version": "1.0",
"manifest_version": 2,
"description": "Ctrl+F, but better",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"*://*/*"
],
"background":{
"scripts": ["script.js"],
"persistent": true
},
"content_scripts":[
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"],
"run_at": "document_end"
}
]
}
script.js:
var bkg = chrome.extension.getBackgroundPage();
function eventHandler(){
var input = document.getElementById("find");
var text = input.value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var tab = tabs[0];
var url = tab.url;
chrome.tabs.sendMessage(tab.id, {method: "getDocuments"}, function(response){
bkg.console.log("Hello from response!");
bkg.console.log(response);
});
});
}
content_script.js:
var bkg = chrome.extension.getBackgroundPage();
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.method == "getDOM"){
sendResponse({data : bkg.document});
}else{
sendResponse({});
}
});
There are quite a few issues with your code (see my comment above).
Some suggestions/considerations first:
Do not inject your content script into all webpages. Inject programmatically and only when the user wants to search.
It might be a better idea to do the "searching" right in the content script, where you have direct access to the DOM and can manipulate it (e.g. highlight search results etc). You might need to adjust your permissions if you go for this approach, but always try to keep them to a minimum (e.g. don't use tabs where activeTab would suffice, etc).
Keep in mind that, once the popup is closed/hidden (e.g. a tab receives focus), all JS executing in the context of the popup is aborted.
If you want some sort of persistence (even temporary), e.g. remembering the recent results or last search term, you can use something like chrome.storage or localStorage.
Finally, sample code from my demo version of your extension:
Extension files organization:
extension-root-directory/
|
|_____fg/
| |_____content.js
|
|_____popup/
| |_____popup.html
| |_____popup.js
|
|_____manifest.json
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": true,
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["fg/content.js"],
"run_at": "document_end",
}
],
"browser_action": {
"default_title": "Test Extension",
"default_popup": "popup/popup.html"
}
}
content.js:
// Listen for message...
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// If the request asks for the DOM content...
if (request.method && (request.method === "getDOM")) {
// ...send back the content of the <html> element
// (Note: You can't send back the current '#document',
// because it is recognised as a circular object and
// cannot be converted to a JSON string.)
var html = document.all[0];
sendResponse({ "htmlContent": html.innerHTML });
}
});
popup.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
Search:
<input type="text" id="search" />
<input type="button" id="searchBtn" value=" Find "
style="width:100%;" />
</body>
</html>
popup.js:
window.addEventListener("DOMContentLoaded", function() {
var inp = document.getElementById("search");
var btn = document.getElementById("searchBtn");
btn.addEventListener("click", function() {
var searchTerm = inp.value;
if (!inp.value) {
alert("Please, enter a term to search for !");
} else {
// Get the active tab
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
// If there is an active tab...
if (tabs.length > 0) {
// ...send a message requesting the DOM...
chrome.tabs.sendMessage(tabs[0].id, {
method: "getDOM"
}, function(response) {
if (chrome.runtime.lastError) {
// An error occurred :(
console.log("ERROR: ", chrome.runtime.lastError);
} else {
// Do something useful with the HTML content
console.log([
"<html>",
response.htmlContent,
"</html>"
].join("\n"));
}
});
}
});
}
});
});
I am trying to append a div to page of current active tab. However I am getting this error:
Error during tabs.executeScript: Cannot access contents of url ....
Extension manifest must request permission to access this host.
My Code: (show_loader.js)
var dv = document.createElement('div');
dv.id = 'myid';
dv.innerHTML = 'test';
document.body.appendChild(dv);
However when I put this code:
document.body.style.backgroundColor = 'green';
It works as expected and background color of current tab is changed with no other change except for the code in show_loader.js file which is run from popup.js like this:
chrome.tabs.executeScript(null, {file: "show_loader.js"});
My Manifest file also does have:
"permissions":
[
"tabs",
"notifications",
"http://*/",
"https://*/"
],
So I wonder why it gives above error when I try to do anything else other than setting background color. Even simple alert or console.log alone on that page gives same above mentioned error.
How to fix that ?
Update: Complete Relevant Code
Manifest:
{
... name and description ...
"icons":
{
"16" : "img/icon.png",
"48" : "img/48.png",
"128" : "img/128.png"
},
"permissions":
[
"tabs",
"notifications",
"http://*/*",
"https://*/*"
],
"browser_action":
{
"default_icon": "img/icon.png",
"default_title": "Page title",
"default_popup": "popup.html"
}
}
popup.js
// send data to server for saving
$('#btn').click(function(){
chrome.tabs.executeScript(null, {file: "show_loader.js"});
$loader.show();
var data = $(this).closest('form').serialize();
$.ajax({.....});
});
window.onload = function(){
var $loader = $('#loader');
$loader.show();
chrome.tabs.getSelected(null, function(tab) {
//console.log(tab);
$('#url').val(tab.url);
$('#title').val(tab.title);
$loader.hide();
});
};
popup.html
<html>
<head>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<form action="" method="post" name="frm" id="frm">
<table border="0" cellpadding="3" cellspecing="0" width="370">
......
</table>
</form>
<script src='js/jquery.js'></script>
<script src='popup.js?v=014423432423'></script>
</body>
</html>
show_loader.js
console.log($); // doesn't work
// document.body.style.backgroundColor = 'green'; // WORKS
Code which worked
manifest.json
{
"name": "Manifest Permissions",
"description": "http://stackoverflow.com/questions/14361061/extension-manifest-must-request-permission-to-access-this-host",
"version": "1",
"manifest_version": 2,
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"notifications",
"http://*/",
"https://*/"
]
}
popup.html
<html>
<head>
<script src="back.js"></script>
</head>
<body>
<button id="tmp-clipboard">Click Me</button>
</body>
</html>
back.js
document.addEventListener("DOMContentLoaded", function () {
document.getElementById('tmp-clipboard').onclick = function () {
chrome.tabs.executeScript(null, {
file: "script.js"
});
}
});
script.js
var dv = document.createElement('div');
dv.id = 'myid';
dv.innerHTML = 'test';
document.body.appendChild(dv);
Try Eliminating deprecated chrome.tabs.getSelected from your code and use chrome.tabs.query instead.
Sample Usage
chrome.tabs.query({
"currentWindow": true,
"status": true,
"active": true //Add any parameters you want
}, function (tabs) {//It returns an array
for (tab in tabs) {
//Do your stuff here
}
});
Edit 1
If you intention is to capture active browsing tab in current window where he clicked browser action use this code
chrome.tabs.query({
"currentWindow": true,//Filters tabs in current window
"status": "complete", //The Page is completely loaded
"active": true // The tab or web page is browsed at this state,
"windowType": "normal" // Filters normal web pages, eliminates g-talk notifications etc
}, function (tabs) {//It returns an array
for (tab in tabs) {
$('#url').val(tabs[tab].url);
$('#title').val(tabs[tab].title);
$loader.hide();
}
});
The manifest v3 uses a different permission schema. This is what worked for me:
"host_permissions": [
"https://music.youtube.com/*"
],