I am trying to do something simple and somehow it does not work...
I am trying to build a simple chrome extension that when you click on it it is showing the URL of the TAB in a simple HTML. How can I do it? this is the code:
manifest.json
{
"name": "MY EXTENSION",
"version": "1.0",
"description": "the DESCRIPTION",
"browser_action": {
"default_icon": "icon.png",
"popup": "main.html"
},
"permissions": [
"tabs"
]
}
End of manifest.json
Main.html:
<html>
<head>
<title>my title</title>
<script src="jquery.json-2.3.min.js"></script>
<script type="text/javascript">
var pageUrl = null;
var pageTitle = null;
var Title1 = 'lala';
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
function get(){
chrome.tabs.getSelected(null, function(tab) {
pageUrl = tab.url;
pageTitle = tab.title;
$('#bkmk').attr('value',pageUrl);
$('#title').attr('value',pageTitle);
});
}
</script>
</head>
<body onload="get()">
<p id="currentLink">Loading ...</p>
<hr />
<ul id="savedLinks"></ul>
<tr><td align="right">Link (URL): </td><td><input id='bkmk' name='bkmk' type="text" value="" size="50">
<br><span style="color: red;"></span>
</td></tr>
<script>document.write($bkmk)</script>
</body>
</html>
=============
and I placed the jquery.json-2.3.min.js file in the same folder..
Anything I do I cannot make the HTML to show the URL..
Thanks!!
Elikd
It appers that you are using jQuery... but you don't have the jQuery library included in a <script src="..."></script> block anywhere. If you're using a local copy of jQuery, you need to include the jQuery library file in your extension directory and refer to its relative path in the extension relative to the HTML page (e.g., "jquery.min.js" if it's in the same folder or "lib/jquery.min.js" if it's in a folder called lib).
In the future, you can get a JavaScript console (with a list of errors) by right-clicking your browser action icon and selecting "Inspect popup". See Google's tutorial on debugging Chrome extensions for more information.
Related
I'm making a simple extension that gets URL of the current tab and saves it to the storage when I click a 'create' button and retrieve URL when 'goto' button clicked.
I got undefined tab and url debugging this code. I'm new to chrome extension and javascript and would appreciate your help! :)))
this is my popup.js
$(function() {
$('#create').click(function() {
var tab;
var myUrl;
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs){
tab = tabs[0];
myUrl = tab.url;
});
chrome.storage.sync.set({'newUrl': myUrl});
});
});
popup.html
<script src= "jquery-3.4.1.min"></script>
<script src = "popup.js"></script>;
</head>
<body>
<input type = "button" id = "create" value = "create">
<input type = "button" id = "go" value = "go to">
</body>
manifest.json
"permissions": [
"tabs",
"activeTab",
"bookmarks",
"contextMenus",
"storage",
"*://*/*"
],
chrome.* apis can be accessed from background and popup scripts only.
You have written those chrome.* api in injectedScript or content script.
I am creating a Google Chrome Extension that uses a script that works perfectly well in Google Chrome's console.
However, I am trying to use this same script beyond just printing the information in console.
How would I be able to somehow create HTML elements that contain this information within the popup.html page? I know that this idea might have to use the callback function within
Here is my code:
manifest.json
{
"manifest_version": 2,
"name": "MR QC Auditor View",
"version": "1.0",
"description": "This Google Chrome extension shows Ad ID's for print ads, and then links to Ad Tagger for tagging corrections",
"icons": {
"128": "MRLogo128.png",
"48": "MRLogo48.png",
"16": "MRLogo16.png"
},
"browser_action":{
"default_icon": "MRLogo16.png",
"default_popup": "popup.html"
},
"permissions": [
"storage",
"tabs",
"activeTab"
]}
popup.html:
<!DOCTYPE html>
<html>
<head>
<title>MR QC Auditor View</title>
<script src="jquery-3.3.1.min.js">
</script>
<script src="popup.js">
</script>
</head>
<body>
<img src="MRLogo128.png"/>
<h1>Current Ad's Brand: <h1><span id="brandNameText"></span>
<h2>Link To Ad Tagger</h2><span>Link</span>
</body>
</html>
popup.js:
// Current Post To Look At:
// https://stackoverflow.com/questions/4532236/how-to-access-the-webpage-dom-rather-than-the-extension-page-dom
// Related Google + Group Post:
// https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/9Sue8JRwF_k
// Use chrome.runtime.onMessage()
// Documentation:
// https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript
// chrome.tabs.executeScript():
// https://developer.chrome.com/extensions/tabs#method-executeScript
/*
Old Code Block;
chrome.tabs.executeScript({file: 'jquery-3.3.1.min.js'}, function () { chrome.tabs.executeScript({code: 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); ', allFrames: true}, function(stuff){
chrome.runtime.sendMessage({greeting: "hello"}, function(){
// Call chrome.runtime.sendResponse()
// console.log("DOM Content Sent To Chrome Extension Webpage");
})
}}); });
*/
// Added an array called "adArray" that utilizes the .push() JavaScript array function
// I need to somehow add this to the popup.html page itself, look for the StackOverflow related pages.
chrome.tabs.executeScript({file: 'jquery-3.3.1.min.js'}, function (adArray) { chrome.tabs.executeScript({code: 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); var adArray = []; for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid")); adArray.push($(printAds[i]).attr("data-adid"))}', allFrames: true}); });
/*
Console Based Code That Works:
$("#ad-image printadviewable pointer").find("img").attr("data-adid");
var printAds = document.getElementsByClassName("ad-image printadviewable pointer");
for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid"));}
*/
// One Line Version For Code Dictionary Key
// 'var printAds = document.getElementsByClassName("ad-image printadviewable pointer"); for (var i = 0; i<printAds.length; i++){console.log("Current Ad Id = " + $(printAds[i]).attr("data-adid"));}'
im making a chrome extension and i have a problem loading a file...
I want to load a file when i select an option in the popup.html file
for example, if i select option1 i want eventPage1.js, to be loaded, and if i select option2 i want eventPage2.js to be loaded, but not the two at the same time, just one.
This its my popup.html file
<!DOCTYPE html>
<html>
<form>
Paises en el menu contextual:
<br>
<div>
<input type="radio" id="opcion1" name="opcion" value="opcion1" onclick= <script src="eventPage1.js"></script>
<label for="opcion1">Todos los paises</label>
<input type="radio" id="opcion2" name="opcion" value="opcion2" onclick= <script src="eventPage2.js"></script>
<label for="opcion2">Solo Mexico</label>
</div>
</form>
</body>
</html>
each eventpage file, its a context menu...
this its how my manifest file looks like
{
"manifest_version": 2,
"name": "help me",
"author": "me man",
"version": "1.1.4",
"description": "test test",
"browser_action":
{
"default_icon": "icon-large.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["menuSelection.js"]
},
"permissions": [
"storage",
"contextMenus"
],
"icons": {
"16": "icon-bitty.png",
"48": "icon-small.png",
"128": "icon-large.png"
}
}
another problem that i have, its that when i select an option... save that option in storage so everytime i use the extension its automatically loaded that option
Event page is a technical term for the page declared in "background" section of manifest.json with "persistent": false. It's not just a name. It's a special context which exists only for that single hidden page. Make sure to read the extension architecture overview.
Inline code in html file doesn't work in extension pages by default for security reasons (the onclick attribute in your html). Handle all events in a separate js file
The input tags in your html aren't closed, and actually malformed. There's no opening <body>.
To save the options use chrome.storage API or the old primitive string-based localStorage
To dynamically load js files, add a script element dynamically into head with its src property set to the name of the file to load. Or use the modern require()-based approach. However, you might want to start learning using a single script file.
Don't use form: the browser is not a web server so the page cannot be submitted. It will simply reload and you'll lose all data. Of course you can prevent the submit event in a listener but it defeats the purpose of using a form. Instead process a change immediately.
popup.html:
<!DOCTYPE html>
<html>
<body>
Paises en el menu contextual:
<div>
<label><input type="radio" name="opcion" value="opcion1">Todos los paises</label>
<label><input type="radio" name="opcion" value="opcion2">Solo Mexico</label>
</div>
<script src="popup.js"></script>
</body>
</html>
popup.js:
function setRadio(name, value) {
const el = document.querySelector(`input[name="${name}"][value="${value}"]`);
if (el && !el.checked) {
el.checked = true;
}
}
chrome.storage.sync.get('opcion', data => {
setRadio('opcion', data.opcion);
});
document.onchange = event => {
if (event.target.name == 'opcion') {
const value = event.target.value;
chrome.storage.sync.set({opcion: value});
switch (value) {
case 'opcion1':
doSomething1();
break;
case 'opcion2':
doSomething2();
break;
}
}
};
chrome.storage.onChanged.addListener((changes, area) => {
if (area == 'sync' && 'opcion' in changes) {
setRadio('opcion', changes.opcion.newValue);
}
});
I think you would probably want to do something like this when you click on the selected option:
<script type="text/javascript">
function LoadJavascriptFile(fileToLoad){
var script = document.createElement("script");
script.id = "customScript";
script.type = "text/javascript";
script.src = "fileToLoad";
document.getElementsByTagName("head")[0].appendChild(script);
}
</script>
On you option select you'd call
LoadJavascriptFile("PathToMyFile.js")
You'd then check if the Script ID exists in the header. If it does, update the SRC otherwise create the SRC
I'm trying to create an extension for Chrome Browser. It should include options where the behaviour of an newly created tab can be chosen (e.g. opening the tab in background or in foreground). The setting should be stored with localStorage.
As I'm new in programming JavaScript, I took the example code from http://developer.chrome.com/extensions/options and tried to customise it. This is what I have so far, and it is working (which means the chosen radio button is saved when page is reloaded) in jsfiddle: http://jsfiddle.net/yczA8/
I was really happy to see it working. But after having created and loaded the Chrome extension, it wasn't working any more. Also opening the html-File in Chrome Browser doesn't show the same behaviour as it does in jsfiddle. Why not? Where's the problem?
This is my popup.html:
<!DOCTYPE html>
<html>
<head>
<style>
body {
min-width: 200px;
min-heigth: 100px;
overflow-x: hidden;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<h3>Neuer Tab im:</h3>
<form method="post">
<input type="radio" name="tabVerhalten" value="tabVordergrund" />Vordergrund
<br />
<input type="radio" name="tabVerhalten" value="tabHintergrund" />Hintergrund
</form>
<div id="status"></div>
<button id="save">Save</button>
</body>
</html>
This one is popup.js:
// Saves options to localStorage.
function save_options() {
var tabVerhalten1 = document.getElementsByName('tabVerhalten')[0].checked;
var tabVerhalten2 = document.getElementsByName('tabVerhalten')[1].checked;
var tabVerhaltenIndex;
if (tabVerhalten1)
tabVerhaltenIndex = 0;
else if (tabVerhalten2)
tabVerhaltenIndex = 1;
localStorage.setItem("tabVerhalten", tabVerhaltenIndex);
// Update status to let user know options were saved.
var status = document.getElementById("status");
status.innerHTML = "Ă„nderungen gespeichert.";
setTimeout(function () {
status.innerHTML = "";
}, 750);
}
// Restores select box state to saved value from localStorage.
function restore_options() {
var storedVal = localStorage.getItem("tabVerhalten");
if (!storedVal) {
return;
}
document.getElementsByName('tabVerhalten')[storedVal].checked = true
}
restore_options();
document.addEventListener('DOMContentLoaded', restore_options);
document.querySelector('#save').addEventListener('click', save_options);
and finally the manifest.json:
{
"manifest_version": 2,
"name": "TEST",
"version": "1.0",
"author": "STM",
"description": "Description",
"permissions": ["contextMenus", "tabs"],
"background": {"scripts": ["script.js"]},
"icons": {"16": "16.png", "48": "48.png", "128": "128.png"},
"browser_action": {"default_icon": "48.png", "default_popup": "popup.html"}
}
Try doing this instead:
document.addEventListener("DOMContentLoaded", function() {
restore_options();
}, false);
I MADE THE FOLLOWING CHANGES:
I removed method="post"
I moved <script src="popup.js"></script> after all the other script
I changed the parameters for the addEventListener() method
HERE ARE THE CHANGED SCRIPTS
popup.html:
<!DOCTYPE html>
<html>
<head>
<style>
body {
min-width: 200px;
min-heigth: 100px;
overflow-x: hidden;
}
</style>
</head>
<body>
<h3>Neuer Tab im:</h3>
<form>
<input type="radio" name="tabVerhalten" value="tabVordergrund" />Vordergrund
<br />
<input type="radio" name="tabVerhalten" value="tabHintergrund" />Hintergrund
</form>
<div id="status"></div>
<button id="save">Save</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
// Saves options to localStorage.
function save_options() {
var tabVerhalten1 = document.getElementsByName('tabVerhalten')[0].checked;
var tabVerhalten2 = document.getElementsByName('tabVerhalten')[1].checked;
var tabVerhaltenIndex;
if (tabVerhalten1)
tabVerhaltenIndex = 0;
else if (tabVerhalten2)
tabVerhaltenIndex = 1;
localStorage.setItem("tabVerhalten", tabVerhaltenIndex);
// Update status to let user know options were saved.
var status = document.getElementById("status");
status.innerHTML = "Ă„nderungen gespeichert.";
setTimeout(function () {
status.innerHTML = "";
}, 750);
}
// Restores select box state to saved value from localStorage.
function restore_options() {
var storedVal = localStorage.getItem("tabVerhalten");
if (!storedVal) {
return;
}
document.getElementsByName('tabVerhalten')[storedVal].checked = true
}
restore_options();
document.addEventListener('DOMContentLoaded',function() {restore_options();}, false);
button_thing = document.querySelector('#save').addEventListener('click',function() {save_options();}, false);
Your problem is, in JSFiddle you are running the JS-code onLoad and in your files you are running the JS-code in the header.
If you change it in your JSFiddle, it's no longer working as you can see here: JSFiddle.
So, what can you do to solve this issue?
There are different ways, I'll recommend to load your JS-code on load, like JSFiddle does. To do this, add the onload event to your body tag. There you call a function named 'loadMyScript();' or something like this:
<body onload="loadMyScript();">
For the next step, you have the choice: You can put your whole code in the loadMyScript() function or you import your script with the loadMyScript() function. I didn't test those ways, so I can't tell you which one is working better or which one is simpler but you should try the import-script-way first, because I think this could avoid issues.
Little example of the import-script-way:
<head>
<script>
function loadMyScript() {
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "popup.js";
document.body.appendChild(js);
}
</script>
<!-- YOUR HTML HEAD HERE -->
</head>
<body onload="loadMyScript();">
<!-- YOUR HTML BODY HERE -->
</body>
I am creating a Chrome Extension that upon clicking the extension icon will present the user with a button, clicking that button will open a new tab which will display a parameter passed to it from the original page. The strange thing is that this will work if I debug it (i.e. right click the extension icon and click "Inspect popup"), but it will just show a blank page upon clicking the button if I'm not debugging.
manifest.json
{
"name": "test name",
"version" : "0.1",
"description": "test description",
"browser_action":
{
"default_icon": "icon_128.png",
"popup": "test.html"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
}
test.html
<HTML>
<BODY>
<script type="text/javascript">
var currentWindowID = -1;
window.onload = function(e){
chrome.windows.getCurrent(function(w)
{
currentWindowID = w.id;
});
}
function openNextPage(){
console.log("in openNextPage");
chrome.tabs.create(
{url: "test2.html"},
function(tab)
{
chrome.tabs.sendRequest(tab.id, {someParam: currentWindowID});
}
);
console.log("exiting openNextPage");
}
</script>
<input type="button" value="Show next page" onClick="openNextPage()">
</BODY>
</HTML>
test2.html
<HTML>
<script type="text/javascript">
chrome.extension.onRequest.addListener(function(request)
{
document.write("<h1>test</h1>");
document.write("<h2>value=" + request.someParam + "</h2>");
});
</script>
</HTML>
The browser will activate the new tab when it is created, and your popup will be closed. Therefore, the callback is never called from chrome.tabs.create. The background page is a more proper place for such code.
test.html
<HTML>
<BODY>
<script type="text/javascript">
var currentWindowID = -1;
window.onload = function(e){
chrome.windows.getCurrent(function(w)
{
currentWindowID = w.id;
});
}
function openNextPage() {
var bg = chrome.extension.getBackgroundPage();
bg.openNextPage(currentWindowID);
}
</script>
<input type="button" value="Show next page" onClick="openNextPage()">
</BODY>
</HTML>
background.html
<HTML>
<BODY>
<script type="text/javascript">
function openNextPage(currentWindowID) {
console.log("in openNextPage");
chrome.tabs.create(
{url: "test2.html"},
function(tab)
{
chrome.tabs.sendRequest(tab.id, {someParam: currentWindowID})
}
);
console.log("exiting openNextPage");
}
</script>
</BODY>
</HTML>