JS bookmarklet issue: Code works in console, fails in bookmarklet - javascript

Using a JS bookmarklet to set a custom field in the Wordpress Edit Post screen. The following code works well when I copy/paste it into the console (latest Chrome stable):
document.getElementById('metakeyselect').value = "foo";
document.getElementById('metavalue').value = "bar";
document.getElementById('meta-add-submit').click();
Works without a hitch; I jut paste this into the console, and a new custom var is added to the post (I have "foo" as a var name in WP already).
In bookmarklet form, this same code looks like this:
javascript:document.getElementById('metakeyselect').value = "foo";document.getElementById('metavalue').value = "bar";document.getElementById('meta-add-submit').click();
And it fails: When I click it, the Name and Value boxes are filled in, but nothing gets submitted. The console shows the following error:
Uncaught TypeError: Cannot call method 'click' of null
Any idea why? Same exact code, same browser, same page.

I had a similar problem and am quite sure that's what causes your code to break too.
My minimal example would be the following code on this website (should work afor the entire stackoverflow.com domain):
document.getElementsByName("q")[0].value="foo";
This should write "foo" to the search field (that has no id but is the only element with the name "q"). Both web console and bookmarklet will set the value as expected but the bookmarklet will also change the page to an empty header and a body containing only the word "foo" after a short delay. Assuming that this is not a random bug that only applies to me, the reason for the thrown exception in your example is that the bookmarklet sets the value "foo", then "bar" but changes the content of the web page to "foo", then "bar" before your last line terminates.
Unfortunately I don't know the reason for this behaviour (I found this question looking for that exact information) but that is what most likely causes the TypeError in your excample.
It is possible that the same code runs without any problems when used in a Greasemonkey script (e.g. as the onclick script of a button you added using Greasemonkey).
[Edit:] Apparently, if a bookmarklet evaluates to anything other than undefined, the inner html of the website is replaced by a string representation of that value. To make sure that the bookmarklet evaluates to undefined, you can just type undefined as the last line outside of any condition block. unfortunately that means it is less likely that my assumption toward OP's error is correct but at least future visitors still might find this information usefull.

It looks like the code you use in console works ok.
It seems like the method you turn console code into a bookmarklet is what might result into an error.
The basic IIFE-construction, i.e. Immediately Invoked Function Expression, looks like this:
javascript:(function () {
/*code here*/
})();
Therefore, the code that is supposed to work might be this.
javascript:(function () {
document.getElementById('metakeyselect').value = "foo";
document.getElementById('metavalue').value = "bar";
document.getElementById('meta-add-submit').click();
})();
Does it solve your problem?

Related

Javascript Errors in Browser capture event with jQuery Listener? Or Response?

OK I'm not really sure how to phrase this question. I want to return the string that drops in my developer console.
Lets say I intentionally want to have an error drop (my script does not freeze I'm using a Simulated Async Loop).
Example:
page.run = (function(){
var eP = $('#someElement').position();
console.log(eP);
})();
Ok lets say we call that knowing that we have no element in the DOM with the id #someElement... besides all the other reasons this example by its self is rubish lets pretend it runs and does not lock up the script so the console would be dropping Errors like: "TypeError: $(...).position(...) is undefined" with the line number of the script going on and on and on... blah. But then wham at some point you load that element it is looking for and it starts returning your console.log(eP);
So Ok now my question....
How Could I hyjack the "TypeError: $(...).position(...) is undefined" and line number script ect when it happens and use it for my own means?
http://www.w3schools.com/js/js_errors.asp
credit goes to James Michael Winters, facebook beat stackoverflow to it sorry :-(
It returns undefined error because parent object-$('#someElement') is null.
Please check not null condition of parent object-$('#someElement') and call the method and print it in console.

javascript expression expected

I am still new a Javascript tried earching and tried the development tool in Chrome, too see if I could find the problem.
Working in Intellij IDEA 13, Java, javascript and xhtml.
My problem is that I have a piece of javascript, then in IDEA when moused over, says that
Expression Expected
the javascript code looks the following
<script type="text/javascript>
function nameOfFunction(){
if(#{trendAnalysisLocationReportController.model.showTargetLine}){
this.cfg.series[this.cfg.data.length-1].pointLabels = {
show: false
};
}
}
<\script>
the method in the if sentence is a java method with a boolean return value.
the error is shown when hovering
'#{'
if Had a look at the following questions, before :
Expected Expression
boolean in an if statement
But didnt get me a solution.
what Iam I doing wrong ?
It looks as though the problem is the part that you've got within the #{...} block. Without knowing the context, it's hard to be sure, but is this something in a view/JSP page that's supposed to be replaced with a property at runtime? The if block will expect the part inside the brackets to be a boolean value, so if that's rendered to either 'true' or 'false' it would execute at runtime but would likely show the error you're seeing in your IDE as it's not actually a valid piece of JavaScript. If, on the other hand, you're expecting to be able to call your Java method/property from your JavaScript code, you're going to need to do something that requests that value from the server-side code - AJAX or similar.
Also worth noting that we can't see what this.cfg is supposed to represent. If that's your entire script block, then there's nothing that defines the cfg object within the current scope.
One last thing, you should change the <\script> end element to as it won't be understood properly by some browsers.

Javascript SetInverval() fireing only once in Firefox [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
setInterval not working (firing only once) in Google Chrome extension
This error only is a problem when document.write() is used.
I am on Mac 10.6.8 Intel.
Here is my script:
setInterval(function(){myFun()},1000);
function myFun() {
document.write('something');
}
The behavior is different in various browsers:
Firefox 12: Only happens once. The browser says "connecting" in the status bar.
Google Chrome and safari: Seems to work correctly.
Note: using setTimeout instead causes everything to behave like firefox (not working).
Using setInterval(myFun},1000), which is supposedly the source of so much error, behaves identically.
Many beginning tutorials use document.write() for "hellow world". However, this funciton is dangerous because it may mess up the script (by nuking the entire program). Here is a safe way to do debug printouts:
Before the script, in between the and in the html, add this:
<div id="myDebug"></div>
In the script, first convert it to a variable that can be called upon:
var myDebug = document.getElementById("myDebug");
When you need to show something, do this:
debug.innerHTML = "some string";
This will show the string in the browser window.
try this:
setInterval(function(){myFun()},1000);
function myFun() {
// Return all elements in document of type 'body'
// (there will only be one)
var bodyArray = document.getElementsByTagName('body');
// get the body element out of the array
var body = bodyArray[0];
// save the old html of the body element
var oldhtml=body.innerHTML;
// add something to the end
body.innerHTML=oldhtml+"somrthing";
}
As others have mentioned, using document.write() will (in some browsers) nuke the script used to update the document, writing to the body (and not the head, where the javascript should be stored) will stop this from happing.
Seems that you miss the semicolon after myFun()
setInterval(function(){myFun();},1000);
function myFun() {
document.write('something');
}
Also make sure you put the function in <body></body>
document.open() results in clearing the document. This function gets called by Firefox before document.write(). Thus your interval is lost.
see W3C Document Object Model HTML

javascript if condition not executing all commands

I'm having one little iritating problem. I have simple if condition in javascript code.
It goes something like this:
if (istinito)
{
alert ('123');
document.getElementById('obavestavanje').value="Pobedi "+ime_igraca+"!!!";
kraj=true;
}
Alert apears when istinito=true, but element with id="obavestenje" never get its value, and variable kraj never is set to true. Variable kraj is global variable, and there are no conflicts with other parts of the JS code.
Any ideas why code stops after alert?
Looks like document.getElementById('obavestavanje') is returning null. You are trying to de-reference the null reference by using document.getElementById('obavestavanje').value which results in null pointer exception. If you look into the console, you should see some exception being raised. It is always a good idea to check if the document.getElementById() is returning a valid object before trying to dereference it.
e.g.
if (istinito)
{
alert ('123');
element = document.getElementById('obavestavanje')
if(element){
element.value="Pobedi "+ime_igraca+"!!!";
}
kraj=true;
}
First advice i could give you:
Use more console logging for debugging. Almost any modern browser got a console to debug and other things.
if (istinito) {
console.log("i am here");
}
from that same console you can also execute commands. Those dom manipulations are easily done from the console. just run them and see if it works.
the code:
document.getElementById('obavestavanje').value = "some value"
looks ok. nothing wrong with it. i guess you don't have an element with id "obavestavanje" ?
Looks like your code is okay. And you are sure you have an element by id 'obavestavanje'. Could you please tell what element is it? Is it a button, textbox or someting like that?
Also the String in the "Pobedi "+ime_igraca+"!!!" , what is 'ime_igraca'? Is it a variable and if it is have you defined this variable somewhere?
Or did you mean to give the value "Pobedi ime_igraca !!!" ??
Thanks
Ranis MK

Print Element names in Console Use Firebug

I want to listing all input elements in console of firebug so in console window write the followings:
var inputs = $(":input");
console.log(inputs);
but when I press the Run in console appear null
also when I write just var inputs = $(":input"); the console show Undefined I sure the page have a lot of input elements, where is the problem?
There is nothing wrong with the provided snippet.
Though, without specifying what to write (using console.log) firebug will print whatever the last statement returned, when declaring a variable using var the result is always undefined.
var inputs = $(":input"); // firebug printing 'undefined' is valid
var abc = 123; // results in the same thing
Please make sure that the website in question actually uses jQuery (bound to global $), and that there really are input elements present in the DOM.
Also make sure that the jQuery version running is of a version later/equal to 1.0 (:input selector didn't exists until then).
If it has jQuery it probably is of a more recent version, how ever; without you providing us with additional information there is no way to guarantee it.
simply go to the firebug console and wrtie as #refp mentioned the page in question must have jquery included
$(":input")
press run

Categories

Resources