微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将突出显示的元素传递给 popup.js 文件,以便我可以操纵它进行更改

如何解决如何将突出显示的元素传递给 popup.js 文件,以便我可以操纵它进行更改

扩展的清单文件

{
  "manifest_version": 2,"name": "Bookmarker","version": "1.0","description": "Bookmark pages so that you can continue reading it next time","browser_action": {
    "default_popup": "popup.html"
  },"background": {
    "scripts": ["background.js"]
  },"content_scripts": [
    {
      "matches": ["<all_urls>"],"js": ["content.js"]
    }
  ],"permissions": ["activeTab"]
}

content.js 文件,我在其中获取突出显示的元素但无法将其传递给 popup.js 文件


// Look for a "mouse up event"
document.addEventListener('mouseup',selectedText);

// Handle the mouse up event
function selectedText(event) {
  // See what text has been selected by the user
  var selected = window.getSelection().anchorNode.parentNode;
  console.log(selected);

  // Make sure something actually was selected
  // if (selected.length > 0) {
  // Send the message to the background script
  // Can't be sent to the pop-up as the pop-up might
  // not be open
  chrome.runtime.sendMessage({ word: selected });
  // } else {
  //   console.log('error');
  // }
}

从 content.js 文件接收消息并将其传递给 popup.js 文件

// Listen for messages
chrome.runtime.onMessage.addListener(receiver);

// A "global" variable to store the word selected by the user
var word;

// Get the message from the content script
function receiver(request,sender,sendResponse) {
  // Save the word
  word = request.word;
}

console.log(word);

扩展程序的 popup.html 模板

<!DOCTYPE html>
<html lang="en">
  <head>
    <Meta charset="UTF-8" />
    <Meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <Meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1 id="h">Bookmark curent location</h1>
    <button id="highlight">highlight</button>
    <script src="popup.js"></script>
  </body>
</html>

popup.js 文件,我想在其中通过 dom 方法操作突出显示的元素

var word = chrome.extension.getBackgroundPage().word;

console.log(word);

// const selectedButton = document.getElementById('highlight');
// const heading = document.getElementById('h');

// selectedButton.addEventListener('click',() => {});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。