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.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I Need to get source code of current tab when the chrome extension icon is clicked . i have also tried with button click event. Please go through my current code :
manifest.json
{ "name": "UM Chrome Extension!", "version": "1.0",
"description": "To ensure the tracking codes present.",
"icons": {
"128": "TW-Extension-Icon2.png"
}, "background": {
"scripts": [ "background.js"]
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["popup1.js","jquery-1.10.2.js","jquery-ui.js","bootstrap.min.js"]
}
],
"permissions": [
"activeTab","tabs","contextMenus", "http://*/*"
],
"browser_action": {
"default_popup": "popup.html"
},
"manifest_version": 2
}
popup.html
<!doctype html>
<html class="no-js" lang="">
<head>
<script type="text/javascript" src="popup1.js"></script>
</head>
<body style="width: 600px; height: 300px;">
<button value="Test" id="check-1"> </button>
</body>
</html>
and popup.js
window.addEventListener('DOMContentLoaded', function() {
var fbshare = document.querySelector('#check-1');
fbshare.addEventListener('click', function() {
var htmlCode = document.documentElement.outerHTML;
window.alert(htmlCode);
});
});
How to get active tab's source code ? i need to get source code of the page so that i need to search whether the page contains particular tracking code(like GA code).
Thank You
Your manifest has both "content_scripts" (which run in the context of the page on document_idle) and "browser_action" scripts (which run in an isolated context when the extensions menu button is clicked).
In popup.html you reference popup.js, so in popup.js when you call document.documentElement.outerHTML you're getting the content of popup.html, not the active tab.
You reference both popup.js and popup1.js, which is confusing. You're currently running the same code in both the popup and the page context, which is almost guaranteed to break in one or the other. By convention use content.js in "content_scripts" and reference popup.js in the action popup.html.
"content_scripts" run in every page, whether users click on the extension or not. Your current manifest is adding ["popup1.js","jquery-1.10.2.js","jquery-ui.js","bootstrap.min.js"] to every page, which is needlessly slow.
Avoid using jQuery in Chrome extensions. It's fairly large and a browser standardisation library doesn't add much when you know for absolute certain that all your users are on Chrome. If you can't code without it then try to restrict it to just your popup or load it in dynamically.
You set a "scripts": [ "background.js"], which runs constantly in the background and isn't needed at all in your current code. If you need to do things outside of the action button consider using event pages instead.
Use the Chrome API to get from the context of the popup to the page. You need to query chrome.tabs to get the active tab, and then call chrome.tabs.executeScript to execute script in the context of that tab.
Google's API uses callbacks, but in this example I'm going to use chrome-extension-async to allow use of promises (there are other libraries that do this too).
In popup.html (assuming you use bower install chrome-extension-async):
<!doctype html>
<html>
<head>
<script type="text/javascript" src="bower_components/chrome-extension-async/chrome-extension-async.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body style="width: 600px; height: 300px;">
<button value="Test" id="check-1"> </button>
</body>
</html>
In popup.js (discard popup1.js):
function scrapeThePage() {
// Keep this function isolated - it can only call methods you set up in content scripts
var htmlCode = document.documentElement.outerHTML;
return htmlCode;
}
document.addEventListener('DOMContentLoaded', () => {
// Hook up #check-1 button in popup.html
const fbshare = document.querySelector('#check-1');
fbshare.addEventListener('click', async () => {
// Get the active tab
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs[0];
// We have to convert the function to a string
const scriptToExec = `(${scrapeThePage})()`;
// Run the script in the context of the tab
const scraped = await chrome.tabs.executeScript(tab.id, { code: scriptToExec });
// Result will be an array of values from the execution
// For testing this will be the same as the console output if you ran scriptToExec in the console
alert(scraped[0]);
});
});
If you do it this way you don't need any "content_scripts" in manifest.json. You don't need jQuery or jQuery UI or Bootstrap either.
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.
I am developing a chrome extension. This is how my extension is structured:
I have a browser action defined such that clicking on it loads a local HTML file default.html. This is my manifest file:
{
"name": "Example Extension",
"version": "0.1",
"manifest_version": 2,
"browser_action": {
"default_title": "Does nothing.",
"default_icon": "icon.png"
},
"background": {
"scripts": ["extension.js"]
},
"permissions": ["tabs"]
}
This is my extension.js:
chrome.browserAction.onClicked.addListener(function(tab) {
var newURL = chrome.extension.getURL('default.html');
chrome.tabs.create({ url: newURL });
});
This is my default.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" href="jquery-1.10.2.min.js"></script>
<script type="text/javascript" href="donothing.js"></script>
</head>
<body>
<b>It works!</b>
</body>
</html>
I want to access chrome's currently open tabs in donothing.js and display some statistics in the default.html. I learn that I can not access chrome.* APIs within my donothing.js. If I have understood the docs correctly, I should declare and define a content script and pass messages as donothing.js --> contentscript.js --> extension.js and vice versa to achieve what I want to. Is there a simpler way to do this? Can someone explain the need for the content script here?
Thanks,
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".
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);
});
});