如何使用chrome扩展名更改文本粗体?

时间:2018-07-04 04:56:16

标签: javascript html google-chrome-extension

我是编程初学者。我想开发一个简单的Chrome扩展程序,当我单击popup.html中的按钮时,该字体可以粗体显示所拖动的内容。单击默认图标后,我成功使所拖动的内容变为粗体,但是在popup.html中使用该功能创建按钮需要更复杂的方式。

我认为popup.js对于将消息发送到content.js来触发函数boldText()是必需的。我很难使用chrome.tabs.sendMessgge或其他东西来触发该功能,但是失败了。 请给我一些建议。

这是我的代码:

1。 manifest.json

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

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

 "background": {
    "scripts": ["jquery-3.3.1.slim.js", "background.js"]
 },

 "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
 },

"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();
  }
}

function boldText() {
  document.designMode = "on"; // designMode on for execCommand
  document.execCommand('Bold', false);
  document.designMode = "off"; // designMode off for execCommand
  return false;
}

4。 popup.html

<!doctype html>
<html>
  <head>
    <script src="jquery-3.3.1.slim.js"></script>
    <script src="popup.js"></script>
  </head>
  <body>
    <button id="boldButton" value="bold">bold</button>
  </body>
</html>

0 个答案:

没有答案