简体   繁体   中英

Why does this function return undefined when run as a bookmarklet?

I'm trying to create a bookmarklet that will alter the styles of an interface I use daily, in order to make it easier to use. However, when I begin the process of minifying the code I simply get the error of undefined in the console.

What am I doing wrong?

This is my latest attempt. Previous attempts are at the bottom.

javascript:void%20function(){var%20a=document.querySelectorAll(%22.btn%22);a.forEach(function(a){a.setAttribute(%22style%22,%22padding:%2015px%2025px%20!important;%22)})}();

Full:

var matches = document.querySelectorAll('.btn');


matches.forEach(function(item) {
  item.setAttribute("style","padding: 15px 25px !important;");
});

Non URL-encoded bookmarklet:

javascript:void function(){var a=document.querySelectorAll(".btn");a.forEach(function(a){a.setAttribute("style","padding: 15px 25px !important;")})}();

The bookmarklet must return undefined , otherwise it won't execute the code properly (it may refresh the page, open the input instead of staying on the page etc). So undefined is not an error, it is a normal matter for any bookmarklet, and the only viable option.

The problem comes if the bookmarklet does not do what it is supposed to. As for your code, your full code that retrieves elements with className 'btn' seems like working .

The issue is just the bookmarklet construction, it might be better to use IIFE-construction , ie Immediately Invoked Function Expression:

javascript:(function () {
    /*code here*/
})();

Therefore, the working bookmarklet code is supposed to be like this:

javascript:(function () {
    var matches = document.querySelectorAll('.btn');
    matches.forEach(function(item) {
        item.setAttribute('style','padding: 15px 25px !important;');
    });
})();

And you can copy-paste the code, without much worrying about spaces (like %20 ) or new lines; the code is supposed to get fixed itself upon inserting it as a bookmarklet.

PS: If someone wishes to make sure it works, you can substitute document.querySelectorAll('*') for document.querySelectorAll('.btn') to apply changes to everything and to see the result right away.

Here is an example:

 /* javascript:(function () {*/ var func1 = function(){ var matches = document.querySelectorAll('.btn'); matches.forEach(function(item) { item.setAttribute('style','padding: 15px 25px !important;'); }); } /* })();*/
 <p><button id='id1' class='btn'>my button1</button></p> <p><button id='id2' class='btn'>my button2</button></p> <p><button id='id3' onclick=func1()>Press to Execute Code</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM