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
Related
I'm making a chrome extension and im wondering how to add a label based on an input box triggered by a button.
I have tried many approaches like changing innerHTML of label i have used .value but nothing has worked. Here is code:
popup.js:
let AddNote = document.getElementById("AddNote");
let input = document.getElementById("input");
function addnote() {
var elem = document.createElement('label');
elem.innerHTML = input.value;
document.getElementsByTagName('body')[0].appendChild(elem);
}
chrome.storage.sync.get("note", ({ note }) => {
AddNote.addEventListener("click", addnote);
});
popup.html:
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<form>
<button id="AddNote">+</button>
<input type="text" id="input"></input>
<label id="label"></label>
</form>
</body>
</html>
background.js:
let note = '';
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ note });
console.log('Set note variable to empty.', `note: ${note}`);
});
manifest.json:
{
"name": "name",
"description": "desc.",
"version": "1.0",
"manifest_version": 3,
"service_worker": "background.js",
"action": {
"default_popup": "popup.html"
}
}
let AddNote = document.getElementById("addNotes");
AddNote.addEventListener("click", function () {
let elem = document.createElement('label')
let space = document.createElement('br')
elem.innerHTML = input.value;
document.getElementsByTagName('body')[0].appendChild(space);
document.getElementsByTagName('body')[0].appendChild(elem);
});
/* chrome.storage.sync.get("note", ({ note }) => {
AddNote.addEventListener("click", addnote);
});
*/
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<button id="addNotes">+</button>
<input type="text" id="input">
<label id="label"></label>
</body>
</html>
What I added/changed
1. The input tag is empty, which means that the closing tag isn't required. And so I removed it's closing from your HTML.
2. I commented around `chrome.storage.sync.get()`, since this will only work if stack snippet was an extension, which it isn't.
3. With the help of `br` tags, each time before adding the label I added a br, just so all the labels won't appear on the same row. You can remove that if you don't need it.
The main problem
In HTML5, If you have a form tag without an `action` attribute then the data will be sent to its own page. That being said, when clicking the `+` button the page would redirect to itself (looks like a refresh), resulting in the wrong conclusion thinking your code didn't work. I removed the `form` tag from your HTML.
I'm new to stackoverflow and even new to programming. I just started to learn to progam online and I am trying to make my first google extension.
(but because I am a complete newbie the code might also look terrible - and not efficient)
I want to make a google extension that hides/shows certain threads on a forum (related to facebook, instagram, twitter, ...) based on the values of check boxes in the popup.html of the google extension.
I have most of the code working.
If you click the google extension a pop up is shown and check boxes can be set. After hitting the 'instellingen bewaren' button these settings are saved to chrome.storage and implemented.
Also when you are on the forum and click the chrome extension the filtering of the threads is done based on your last settings.
The problem I have is that I want the filtering to be done alread when the forum page is loaded. I now always have to click the chrome extension icon to start the filtering. If I go to another page on the forum I need to click the extension again to start filtering again.
I have a feeling that all the things I am trying are resulting in the code to be executed after loading the popup.html instead of loading the forum page (at least that is what I conclude when I look at the console of both pages and perform some console.log commands).
Things I tried:
making a background.js file and using the command (also updated the manifest.json file): chrome.tabs.onUpdated.addListener
placing this in my content.js file:
document.addEventListener("DOMContentLoaded", filter);
or
chrome.tabs.onUpdated.addListener
or
window.
This is the current code:
manifest.json
{
"manifest_version": 2,
"name": " Schifters tool",
"permissions": [ "tabs", "activeTab", "storage" ],
"version": "0.1",
"icons": {
"128": "images/S-128.png",
"16": "images/S-16.png",
"48": "images/S-48.png"
},
"browser_action": {
"default_icon": "images/schifters.png",
"default_popup": "popup.html"
},
"description": " Schifters Tool",
"content_scripts": [
{
"matches": [
"https://schifters.be/viewforum.php*"
],
"js": ["content.js"]
}
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Schifters Tool</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous">
</head>
<body>
<div class="modal-header">
<h1 class="logo">
Schifters Tool
<span href="https://schifters.be/index.php" class="version">(1.0.0)</span>
</h1>
</div>
<form>
<div class="activeerFilters">
<p>Geef aan welke posts verborgen moeten worden:</p>
</div>
</form>
<form>
<div class="filters">
<label for="facebook"><input id="facebook" type="checkbox" name="filtering"> Facebook wedstrijd</label>
</div>
</form>
<button id="save">Instellingen bewaren</button>
<div id="status"></div>
<script src="content.js"></script>
</body>
</html>
content.js
// Saves options to chrome.storage
function save_options() {
var facebook = document.getElementById('facebook').checked;
chrome.storage.sync.set({
facebookStatus: facebook,
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Instellingen zijn bewaard';
setTimeout(function() {
status.textContent = '';
}, 750);
filterAlles();
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
facebookStatus: false,
}, function(items) {
document.getElementById('facebook').checked = items.facebookStatus;
// filtering of the threads
filterAlles();
});
}
function filterAlles() {
filterFacebook();
}
function filterFacebook() {
if(document.getElementById('facebook').checked) {
chrome.tabs.executeScript(null, {file: "verbergFacebook.js"});
} else {
chrome.tabs.executeScript(null, {file: "toonFacebook.js"});
}
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', save_options);
toonFacebook.js
{
// place all posts in an Array
const topics = Array.from(document.querySelector('[class="forumbg"]').querySelectorAll('ul>li'));
// show facebook posts
for (var i = 0; i < topics.length; ++i) {
// console.log(topics[i].textContent);
if (topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]') !== null ){
console.log('ok')
topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]').parentNode.parentNode.style.display = "";
} else {
// console.log('nok')
}
}
}
verbergFacebook.js
{
// place all posts in an array
const topics = Array.from(document.querySelector('[class="forumbg"]').querySelectorAll('ul>li'));
// hide all facebook posts
for (var i = 0; i < topics.length; ++i) {
// console.log(topics[i].textContent);
if (topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]') !== null ){
console.log('ok')
topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]').parentNode.parentNode.style.display = "none";
} else {
// console.log('nok')
}
}
}
and like the last 2 js. files there a a lot of extra files. Each time one for hiding a certain type of threads and one for showing a certain type of threads.
Maybe it is not efficient to have this code in ~20 different files? But I couldn't get my checkbox values working in these .js files.?
I expect the chrome extension to filter the threads on the forum (based on the settings of the check boxes from last time) immediately after loading the forum page.
The filter option already works when the extension popup is shown or when you change checkbox settings and click the button on the popup.html page.
But this last function is a mystery for me :)
Thnx in advance!
I' have it working. (more ore less)
The setup is as follows:
Manifest.json
{
"manifest_version": 2,
"name": " Schifters tool",
"permissions": [ "tabs", "activeTab", "storage" ],
"version": "0.1.1",
"icons": {
"128": "images/Schifters.png",
"16": "images/Schifters-16x16.png",
"32": "images/schifters-32x32.png"
},
"browser_action": {
"default_icon": "images/schifters.png",
"default_popup": "popup.html"
},
"description": " Schifters Tool",
"content_scripts": [
{
"matches": [
"https://schifters.be/viewforum.php*"
],
"js": ["content.js", "popup.js"]
}
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Schifters Tool</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous">
</head>
<body>
<div class="modal-header">
<h1 class="logo">
<img class="logo-icon" src="images/Schifters.png"> Schifters Tool
<span href="https://schifters.be/index.php" class="version">(0.1.1)</span>
</h1>
</div>
<form>
<div class="activeerFilters">
<p>Geef aan welke posts verborgen moeten worden:</p>
<p><label for="activeerFilters"><input id="activeerFilters" type="checkbox" name="activeerFiltering">Activeer de filter opties</label></p>
</div>
</form>
<form>
<div class="filters">
<label for="gespeeld"><input id="gespeeld" type="checkbox" name="filtering"> <img src="./images/GESPEELD.png" alt="GESPEELD"> GESPEELD</label>
<label for="facebook"><input id="facebook" type="checkbox" name="filtering"> <img src="./images/facebookWedstrijd.png" alt="Facebook wedstrijd"> Facebook wedstrijd</label>
</div>
</form>
<button id="save">Instellingen bewaren</button>
<div id="status"></div>
<script src="content.js"></script>
<script src="popup.js"></script>
</body>
</html>
content.js
var topics = Array.from(document.querySelector('[class="forumbg"]').querySelectorAll('ul>li'));
function filterAlles(){
chrome.storage.sync.get({
activeerFiltersStatus: false,
gespeeldStatus: false,
facebookStatus: false
}, function(items) {
console.log("we zitten in de loop van de nieuwe functie");
for (var i = 0; i < topics.length; ++i)
{
if ( items.activeerFiltersStatus &&
((topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]') !== null && items.facebookStatus) ||
(topics[i].querySelector('[title="Markering verwijderen"]') !== null && items.gespeeldStatus))
)
{
console.log('ok - we gaan filteren');
if (topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]') !== null){
topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]').parentNode.parentNode.style.display = "none";
}
if (topics[i].querySelector('[title="Markering verwijderen"]') !== null){
topics[i].querySelector('[title="Markering verwijderen"]').parentNode.parentNode.parentNode.parentNode.style.display = "none";
}
}
else
{
if (topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]') !== null){
topics[i].querySelector('[style="background-image: url(./images/icons/misc/facebook.png); background-repeat: no-repeat;"]').parentNode.parentNode.style.display = "";
}
if (topics[i].querySelector('[title="Markering verwijderen"]') !== null){
topics[i].querySelector('[title="Markering verwijderen"]').parentNode.parentNode.parentNode.parentNode.style.display = "";
}
}
}} );
}
filterAlles();
(this is now correctly run when my forum page is loaded)
and only one other .js file this time
popup.js
// Saves options to chrome.storage
function save_options() {
var activeerFilters = document.getElementById('activeerFilters').checked;
var gespeeld = document.getElementById('gespeeld').checked;
var facebook = document.getElementById('facebook').checked;
chrome.storage.sync.set({
activeerFiltersStatus: activeerFilters,
gespeeldStatus: gespeeld,
facebookStatus: facebook
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Instellingen zijn bewaard';
setTimeout(function() {
status.textContent = '';
}, 750);
// filterAlles();
chrome.tabs.executeScript(null, {file: "content.js"})
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
activeerFiltersStatus: false,
gespeeldStatus: false,
facebookStatus: false
}, function(items) {
document.getElementById('activeerFilters').checked = items.activeerFiltersStatus;
document.getElementById('gespeeld').checked = items.gespeeldStatus;
document.getElementById('facebook').checked = items.facebookStatus;
if(document.getElementById('activeerFilters').checked) {
document.getElementById("gespeeld").disabled = false;
document.getElementById('facebook').disabled = false;
} else {
document.getElementById("gespeeld").disabled = true;
document.getElementById('facebook').disabled = true;
}
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', save_options);
var checkbox = document.getElementById("activeerFilters");
// Dit zorgt ervoor dat de checkboxen sensitief worden als je de 'activeer filters optie' selecteert
checkbox.addEventListener( 'change', function() {
if(this.checked) {
document.getElementById("gespeeld").disabled = false;
document.getElementById('facebook').disabled = false;
} else {
document.getElementById("gespeeld").disabled = true;
document.getElementById('facebook').disabled = true;
}
});
In this setup the threads are hidden when the page is loaded (based on the last settings of the check boxes in the popup.html file).
When settings are changed in the popup.html file then these changes are also applied.
So is seems to be working.
However I get some errors in console (and I don't know if this is an issue or not).
When I go to the console of the popup.html file I get this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
at popup.js:48
it's referring to this line of code:
document.getElementById('save').addEventListener('click', save_options);
And that seems logical as the 'forum webpage' doesn't have the save button (that button is in the popup.html file).
Do I need to change anything in my code to avoid this? Or can I just ignore it?
The other error is in the popup.html console:
Uncaught TypeError: Cannot read property 'querySelectorAll' of null
at content.js:1
it's referring to this line of code:
var topics = Array.from(document.querySelector('[class="forumbg"]').querySelectorAll('ul>li'));
I think this is because the 'document.' should be changed to 'chrome.tabs.' when run from the popup.html page. But I find it strange that the forum threads are hidden correctly. How is it possible that this is working from the popup.html file if we can't placed the forum threads in an array.
As said in the subject, I need to fill a web form using data locally available as excel tables. I am already making that with a combination of python and autohotkey, but I want to have some level of JavaScript control in order to correctly handle loading times and conditionals. As a web development newbie, I first thought I could just have a local iframe controlling the website where the form is, but I discovered soon enough that XSS thing that does not allow such a hack. I do not have access to the server.
The last iteration of my experiences is with Firefox webextensions, with which I hoped to open a local file (through a html5 file input widget), where I would previously have written my js code to fill the form. But apparently there are also limitations here, and I cannot make any sense out the docs I am looking at. My code is currently like that:
popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="file" id="liquida-file" name="liquida">
<br>
<script src="background-script.js"></script>
</body>
</html>
background-script.js
function handleFiles() {
var fileList = this.files; /* now you can work with the file list */
var myFile = fileList[0]
var reader = new FileReader();
reader.onloadend = function(evt){
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var filedata = evt.target.result;
console.error("Analyzing file data")
console.error(filedata)
var data = JSON.parse(filedata)
console.error(data)
}
};
reader.readAsText(myFile)
}
var inputElement = document.getElementById("liquida-file");
inputElement.addEventListener("change", handleFiles, false);
This works as a standalone file, but not as the popup.html file of my webextension. In this case, none of the console.error lines are ever reached. BTW, here is my manifest.json:
manifest.json
{
"manifest_version": 2,
"name": "My extension",
"version": "1.0",
"description": "Retrieve local data.",
"homepage_url": "http://Nonefornow",
"icons": {
"48": "icons/beautiful-icon.png"
},
"permissions": [
"activeTab"
],
"browser_action": {
"browser_style": true,
"default_icon": "icons/icon.png",
"default_title": "My Ext",
"default_popup": "popup.html"
}
}
Is there any easier way to do what I am doing? I was expecting for this sort of thing to be a common need, am I wrong? And why doesn't my code work?
This problem has been pointed out in this question:
Firefox WebExtensions, get local files content by path.
The solution given there is the following:
function readFile(_path, _cb){
fetch(_path, {mode:'same-origin'}) // <-- important
.then(function(_res) {
return _res.blob();
})
.then(function(_blob) {
var reader = new FileReader();
reader.addEventListener("loadend", function() {
_cb(this.result);
});
reader.readAsText(_blob);
});
};
but in this solution the absolute path has to be passed to the function, like here:
readFile('file:///home/saba/desktop/test.txt', function(_res){
console.log(_res); // <-- result (file content)
});
If you want to load a file from an <input> field you have to pass the path of the file too, because for security reasons you can't retrieve that from the <input> field. My solution was to read the path from an input text field, reducing significantly the usability
html
path: <input type="input" id="importFilePathInput" value="file://" />
<br />
file: <input type="file" id="importFileInput" />
javascript
function importFromfile(){
let filename = jQuery('#importFileInput').val().replace('C:\\fakepath\\', '');
if (!filename) {
console.log('Select a filename');
} else {
let path = jQuery('#importFilePathInput').val() + '/' + filename;
if (!path.startsWith('file://')) {
path = 'file://' + path;
}
fetch(path, {mode:'same-origin'})
.then(function(result){
return result.blob();
})
.then(function(blob){
let reader = new FileReader();
reader.addEventListener('loadend', function(){
Model.save(JSON.parse(this.result)); // your function here
});
reader.readAsText(blob);
});
}
}
Note that unfortunately this solution doesn't work anymore on Firefox 57, giving the error:
TypeError: NetworkError when attempting to fetch resource.
This works as a standalone file, but not as the popup.html file of my webextension.
Aha. I would check the permissions ...
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 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.