简体   繁体   中英

Why does this JavaScript bookmarklet clear the page?

I am experimenting with JavaScript bookmarklet code. I want to

  1. clear the tab content
  2. change the background colour
  3. change the font colour
  4. make the element editable

When I run this code

javascript:document.body.style.background='darkslategray';
document.body.style.color='linen';
document.body.innerHTML='';
document.body.contentEditable=true;

I get a white page. It doesn't matter which order I use the commands. When I run them one by one in the console I get the result I want. A grey page with light font colour I can type in.

Bookmarklets can't run a series of statements unless they are in a function, which is called when the bookmarklet is called.

The answer is to wrap the commands in an anonymous function.

This bookmarklet code will run as a bookmark when the bookmark is called or as a link in a page when the link is clicked. It clears the tab html, and inserts a div to type into.

javascript:(function(){ 
  document.body.innerHTML = 'make notes here'; 
  document.title='your new note';
  var divvy = document.createElement("div"); 
  document.body.appendChild(divvy); 
  divvy.style.background='darkslategray'; 
  divvy.style.color='linen'; 
  divvy.contentEditable=true; 
  divvy.textContent = 'write here' 
})()

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