I finally got one of my first JS scripts running as planned in Firefox. Now I need to switch to chrome.storage because it will otherwise not run in my extension.
Basically I want to update a Value in a HTML file, which can be changed by input in a submission box.
You are very welcome to pick around in my code, and tell me what is totally abnormal. But I am quite new to JS, and am simply trying to get this to work. Since this worked with localstorage, I guess I have to get it to work with chrome storage too. Once I get it to work, cleaning this mess can begin. Thank you in advance! (I am trying to solve this since around 12 hours not. Can't grasp it.)
the error i get when examining the script:
Uncaught Error: Invocation of form get(string) doesn't match definition get(optional string or array or object keys, function callback)
at normalizeArgumentsAndValidate (extensions::schemaUtils:112:11)
at StorageArea.self.(anonymous function) [as get] (extensions::StorageArea:35:14)
at chrome-extension://fcbadpjebgjnohhcihmkopdbnbjjmnod/initialize_id.js:5:26
options.html this is the "settings" file where one inputs the id which shall be changeable.
</head>
<body>
<p>ENTER YOUR ID FROM tsindex.com BELOW</p>
<form>
<input id="ts_id_js_html" type="text" value="128856"></input>
<br>
<br>
<button onclick="store()">Save/Load</button>
</form>
<script src="initialize_id.js"></script>
<script src="options.js"></script>
<script src="load_id.js"></script>
</body>
</html>
options.js this stores the given ID from the input field in chrome.storage.local (before localstorage)
function store(){
var input_id = document.getElementById("ts_id_js_html").value;
chrome.storage.local.set("ts_id_js", input_id);
}
initialize.js if chrome.storage.local is undefined executes X once. else it gets the stored value and replaces the input in the filed.
var init_count;
if (chrome.storage.local.get("ts_id_js") === undefined && init_count == undefined) {
init_count++; //ignore this for now
} else {
document.getElementById("ts_id_js_html").value = chrome.storage.local.get("ts_id_js");
}
load_id_to_popup.js this gets loaded when the popup.html gets opened, and inputs the given ID in the necessary field.
document.getElementById('input_id').dataset.serverid =
chrome.storage.local.get("ts_id_js");
IGNORE ! load_id.js THIS IS CURRENTLY REDUNDANT, ignore this.
document.getElementById("ts_id_js_html").value =
chrome.storage.local.get("ts_id_js");
chrome.storage.local.get is asynchronous, it is mean, Chrome returns value to callback function:
chrome.storage.local.get("ts_id_js", function(obj) {
let value = obj["ts_id_js"];
});
Related
I am working on a project on Google Apps Script. I have a JS function that returns a date (as a text). I also have an HTML document to display a form with several inputs. I would like to prefill one input with the date returned by the JS funtion. It almost works, except it displays "undefined" instead of the date, even though I know the js funtion is working fine.
Here are some code to better understand :
The input where I call the script (don't mind the onmousemove, i just didn"t find anotherway to call the script).
<input type="text" id="deliveryDate" name="deliveryDate" onmousemove="displayActiveDate()">
So it calls the folowing script.
<script>
function displayActiveDate(){
var activeDate = google.script.run.getActiveDate();
document.getElementById("deliveryDate").value = activeDate;
}
</script>
Which in turn calls getActiveDate() which is the separate JS function that returns the date.
If you have any idea on how to solve this, I will be very thankful.
google.script.run.serverSideFunction() returns undefined. In order to get the actual response value from your serverSideFunction() you need to use the withSuccessHandler() method with a callback like so:
google.script.run.withSuccessHandler(onSuccess).serverSideFunction();
function onSuccess(data) {
// do something with the data returned by the serverSideFunction()
}
Also note that you also have withFailureHandler(err) to handle any errors you server-side functions may return.
Here is the full reference
Instead of writing document.getElementById("deliveryDate").value = activeDate; type document.getElementById("deliveryDate").innerHTML= activeDate; in your script
After several years of using Jquery I have decided to learn at least basic Javascript. I have run into what is to me a strange problem.
If I have a script like this that runs on page 1, but do not have the same class's on page 2, all scripts stop running that come after this script.
var numberOfClasses = document.querySelectorAll("li.line");
document.querySelector("p.classes").innerHTML = 'Number of support Links ' + numberOfClasses.length;
If I do not have the "p.classes" on the second page, nothing in the JavaScript file that comes after code that will run. Is this normal? The code is in a JS file that is included at the bottom of the html file on both pages. The code above is for example only
The error message on the second page is TypeError: document.getElementById(...) is null, which refers to the first bit of code in the JS file that is not present on the 2nd page
Thanks for your time
jQuery silently "fails" for these situations. If it doesn't find a selector it just returns an empty jQuery object that you can still call methods from, though they wont do anything.
Example
jQuery('NonExistentElement').html("won't show up")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No error will be thrown.
Native DOM methods like querySelector() don't return an empty object that you can still access methods from. They will either return the element, a list of elements (NodeList,HTMLCollection, etc) or null. Thus if you try to access a property on a return value from one of these you have a potential for failure in the case of a null return
document.querySelector('NonExistentElement').innerHTML = "Won't show up";
This is why you need to check for null before trying to use it
var element = document.querySelector('p.classes');
if(element != null){
element.innerHTML = "your html";
}
var element2 = document.querySelector('p.classes2');
if(element2 != null){
element2.innerHTML = "no error as the if statement fails and so this code wont execute";
}
<p class="classes"></p>
I have a rather standard Google Maps page, using my own API key. The page only does some marker additions by JS and presenting it in a text-box. If the key is invalid or expired or whatever, the following page is displayed.
That is fine, but then I would like to at lest tell the user why it is wrong. The map is accessed by standard:
...
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?key=API_KEY"></script>
</head>
<body>
<div id="map"></div>
<p><input type="text" "readonly" id="status" size=40></p>
...
However, I would like to check that the API key is working and valid, and tell the user if the key is OK or not in that text box.
How can I do that?
PS. The problem with using a callback function in the src=, is that it returns regardless what is the API status, but not actually the status itself. Here is a kludge solution of this.
EDIT: I found an answer in the obscurely and poorly documented callback function, gm_authFailure(), and solved my question with:
function gm_authFailure() {
let apiError = "No or invalid API key!"
document.getElementById('status').value = apiError;
};
You don't even need to specify this callback in your URL, it will use it anyway!
Add this:
function gm_authFailure() { alert('yo'); };
In the global scope. Per this:
https://developers.google.com/maps/documentation/javascript/events#auth-errors
I was wondering if anyone could help me. The problem is javascript isn't storing any variables and is acting up.
<script type="text/javascript" language="javascript">
var name = document.getElementById('text_field').value;
var test = "foobar";
function test_function(){
alert("hello"+test);
}
alert('test '+test);
</script>
The second alert doesnt happen at all, and when i click on the button to trigger the test_function() it alerts out "helloundefined" .
I just don't know what to do, it was working fine then all of a sudden it stopped. I should mention that this is on a php page but that shouldn't make a difference.
If there is no element with the ID text_field, the rest of the code will not run.
try changing:
var name = document.getElementById('text_field').value;
to
var name = document.getElementById('text_field').value || "some default value;
OR
var name;
if(document.getElementById('text_field')) {
name = document.getElementById('text_field').value
} else {
name = "some value"
}
Without seeing the rest of the code, most likely the culprit is this line:
var name = document.getElementById('text_field').value;
If the script block is run before 'text_field' exists, you get an error and the rest of the javascript doesn't execute. The result is that you don't see the alert, and the test variable is never set. You need to call the code after the DOM exists, either by running it in onload (or a ready function in jQuery) or by putting the script block at the end of the page.
Move that script block to bottom of the page. text_field does not exist yet. If you're debugging in a browser, use Chrome or Firefox and make use of the "Console" window in the dev tool bar. It'll tell you things like this...
I'm trying to get a very basic Chrome Native Client application running. What I'd like to do is respond to keystrokes, for example by displaying "You pressed X" whenever a user presses a key. I've been at it all day, but every time I press a key, I get "Uncaught TypeError: Object # has no method 'postMessage'".
The errors are all in the Javascript; the Native Client C++ module works fine.
Javascript in head of document:
myModule = null; // Global application object.
function moduleDidLoad() {
myModule = document.getElementById('mymodule');
alert("module loaded!") // this works
myModule.postMessage('hello'); // this works, and posts 'hello' to the module
// ERROR
document.body.onkeydown = function() {myModule.postMessage('hi');}
}
In page:
<div id="listener">
<script type="text/javascript">
var listener = document.getElementById('listener');
listener.addEventListener('load', moduleDidLoad, true);
</script>
<embed name="nacl_module"
id="mymodule"
width=0 height=0
src="mymodule.nmf"
type="application/x-nacl" />
</div>
I've tried it about 15 different ways: by adding it to the body tag with addEventListener, by adding it directly to the body tag with onKeyDown... nothing works.
I have experience with C/C++ and PHP but my Javascript is really weak. I think I must be missing something fundamental and obvious.
Solved. Elsewhere on the page, the DIV that contains the game module was having its contents changed, which removed the module from memory.