Get highlight text in current window and send it in a popup

孤者浪人 提交于 2019-12-11 02:18:37

问题


I would like to make a chrome extension that use a popup to do :

  1. select text
  2. click on the chrome extension icon
  3. get it in the popup (textarea, ...)

This question was already asked here but Google did updates and the code I found is not working anymore ...

selection.js

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection")
      sendResponse({data: window.getSelection().toString()});
    else
      sendResponse({}); // snub them.
});

popup.html

    <!DOCTYPE html> 
<html>
<head>
<style>
  body { width: 300px; }
  textarea { width: 250px; height: 100px;}
</style>
<script>


function pasteSelection() {
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
      var text = document.getElementById('text'); 
      text.innerHTML = response.data;
    });
  });
}

function getSelectedText(){
   if (window.getSelection){
      var str = window.getSelection();
   }else if (document.getSelection){
      var str = document.getSelection();
   }else {
      var str = document.selection.createRange().text;
   }
   return str;
}

function affichage(){
var sel = getSelectedText();
alert(sel);
}

function addtext() {
    document.form.champ.value = getSelectedText();
}

</script>
</head>
<body>
<form>
<textarea id="text"></textarea>
<button onclick="pasteSelection(); " type="submit">get text</button>
</form>
</body>
</html>

manifest.json

 {
 "name": "Selected Text",
 "version": "0.1",
 "description": "Selected Text",
 "options_page": "page_options.html",
 "browser_action": {
   "default_title": "Selected Text",
   "default_icon": "icon.png",
   "default_popup": "popup.html" 
 },
 "permissions": [
   "tabs",
   "chrome://favicon/",
   "http://*/*", 
   "https://*/*"
 ],
 "content_scripts": [
  {
    "matches": ["http://*/*"],
    "js": ["selection.js"],
    "run_at": "document_start",
    "all_frames": true
  }
 ],
 "manifest_version": 2
}

I thank you in advance for your help :)


回答1:


There are multiple problems in your script

  • chrome.extension.onRequest is deprecated in favor of chrome.extension.onMessage
  • chrome.tabs.sendRequest is deprecated in favor of chrome.tabs.sendMessage
  • CSP will not allow inline scripting and <script> tag in html code.
  • window object of Content Script is different from normal page window object.

After applying multiple changes to code i got it working

manifest.json

Eliminated not applicable sections of manifest

{
 "name": "Selected Text",
 "version": "0.1",
 "description": "Selected Text",
 "browser_action": {
   "default_title": "Selected Text",
   "default_popup": "popup.html" 
 },
 "permissions": [
   "tabs",
   "http://*/*", 
   "https://*/*"
 ],
 "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["selection.js"],
    "run_at": "document_start",
    "all_frames": true
  }
 ],
 "manifest_version": 2
}

popup.html

Ensured popup.html adheres to CSP

<!DOCTYPE html>
<html>

    <head>
        <style>
            body {
                width: 300px;
            }
            textarea {
                width: 250px;
                height: 100px;
            }
        </style>
        <script src="popup.js"></script>
    </head>

    <body>
        <textarea id="text"></textarea>
        <button id="submit">get text</button>
    </body>

</html>

popup.js

Script to pick current tab and send message and update DOM.

function pasteSelection() {
    //Select current tab to send message
    chrome.tabs.query({
        "active": true,
        "currentWindow": true,
        "status": "complete",
        "windowType": "normal"
    }, function (tabs) {
        //It returns array so looping over tabs result
        for (tab in tabs) {

            //Send Message to a tab
            chrome.tabs.sendMessage(tabs[tab].id, {
                method: "getSelection"
            });
        }
    });
}
//Adding a handler when message is recieved from content scripts
chrome.extension.onMessage.addListener(function (response, sender) {

    //Set text to text area
    var text = document.getElementById('text');
    text.value = response.data;
});

// Bind On click event to pasteSelection() function
document.addEventListener("DOMContentLoaded", function () {

    document.getElementById("submit").onclick = pasteSelection;
});

selection.js

Passes selected text to popup.html

 //Add a handler to handle message sent from popup.html
 chrome.extension.onMessage.addListener(function (request, sender) {
     //Hanlde request based on method
     if (request.method == "getSelection")
     //Send selected text back to popup.html
     chrome.extension.sendMessage({
         data: document.getSelection().toString()
     });
     else chrome.extension.sendMessage({}); // snub them.
 });

References

  • tabs.query()
  • tabs.sendMessage()
  • extension.onMessage()
  • extension.sendMessage()
  • CSP


来源:https://stackoverflow.com/questions/14203551/get-highlight-text-in-current-window-and-send-it-in-a-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!