0

I am a programming beginner. I would like to develop a simple Chrome extension that allows to bold for dragged content, when I click the icon.

Here is my code:

1. manifest.json

{
 "manifest_version": 2,
 "name": "test",
 "version" : "1.0",
 "description": "test",

 "content_scripts": [{
    "matches":    ["<all_urls>"],
    "js":         ["content.js"]
 }],

 "background": {
    "scripts": ["background.js"]
 },

 "browser_action": {
    "default_icon": "icon.png"
 },

"permissions": [
    "activeTab",
    "tabs",
    "storage",
    "http://*/*",
    "https://*/*"
 ]
}

2. background.js

chrome.browserAction.onClicked.addListener(buttonClicked);
function buttonClicked(tab) {
  let msg = {
    txt: "hello"
  }
  chrome.tabs.sendMessage(tab.id, msg);
}

3. content.js

chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message, sender, sendResponse) {
  if (message.txt === "hello") {
    var selection = window.getSelection();
    alert(selection);
    boldText(selection);
  }
}

function boldText(selection) {
  alert(selection);
  selection = selection.toString().bold();
  return false;
}
Yurets
  • 3,999
  • 17
  • 54
  • 74
Junsun
  • 33
  • 4
  • Welcome! Are you having a particular problem with a certain part of this code? If so, please tell us the line number and the problem you are having. Thanks – kismert Jul 02 '18 at 16:40

1 Answers1

0

In order to get the text bold modern browsers implements execCommand function that allows to bold, underline etc. on text.

You just have to make all body contentEditable then run exectCommand, like this:

function boldText() {
  document.getElementsByTagName("body")[0].setAttribute("contentEditable", "");
  document.execCommand("bold");
}

I recommend you to always test directly in the console your DOM manipulation (what you do in content.js). (in Chrome hit F12 and then paste the code) More information in Make selected text bold/unbold Hope it helps.

Marcelo Rossi
  • 375
  • 3
  • 6
  • Many thanks! I will try this:) Also, can html tag be used with contentEditable for whole webpage, like ? If it is possible,modifying the webpage could be easily done with just once declaration of contentEditable, I think. – Junsun Jul 03 '18 at 02:12
  • In addition, here is another question. "ContentEditable" attribute may also delete webpage content.I just want to make it bold or italic. Is there anything other than document.execCommand? – Junsun Jul 03 '18 at 04:54
  • I answer this question by myself. If I turn designMode on and off before and after executing the function, the desired document.execCommand can be executed without affecting the remaining contents. Yeah! Thanks for your time, again:) – Junsun Jul 03 '18 at 06:27
  • Hey, that's a good idea. I'm glad the answer helped you. Can you vote up and mark accepted this answer, you'll be very helpful, thanks! – Marcelo Rossi Jul 03 '18 at 13:12