0

manifest file for the extension

{
  "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 file where i am getting the highlighted element but am not able to pass it to the popup.js file


// 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');
  // }
}

receiving message from the content.js file and passing it to the popup.js file

// 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 template for the extension

<!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 file where I want to manipulate the highlighted element through dom methods

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

console.log(word);

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

// selectedButton.addEventListener('click', () => {});
Aman
  • 1
  • [Messaging can't send DOM elements](https://stackoverflow.com/a/38263829) so you'll need to process it in the content script. – wOxxOm Apr 12 '21 at 11:05
  • if I process it on content script then the action will initiate every time the page is loaded I want a button to perform the action – Aman Apr 13 '21 at 12:28
  • There are many ways to split the logic so you'll have to be creative :-) – wOxxOm Apr 13 '21 at 14:31
  • Thank you so much for the help will try it out – Aman Apr 14 '21 at 15:19

0 Answers0