Chrome扩展程序开发尝试使字体变为粗体

时间:2018-07-02 15:28:02

标签: google-chrome-extension

我是编程初学者。 我想开发一个简单的Chrome扩展程序,当我单击图标时,该扩展程序可以粗体拖动内容。

这是我的代码:

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;
}

1 个答案:

答案 0 :(得分:0)

为了使文本变为粗体,现代浏览器实现了execCommand函数,该函数允许对文本进行粗体,下划线等。

您只需要使所有正文内容可编辑即可,然后运行exectCommand,如下所示:

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

我建议您始终始终在控制台中直接测试DOM操作(在content.js中执行的操作)。 (在Chrome中按F12键,然后粘贴代码) Make selected text bold/unbold中的更多信息 希望对您有所帮助。