chrome extension: get specific part of the current tab page in DOM object and display it in either popup.html or new html page?

北城余情 提交于 2020-01-04 10:58:09

问题


IS there any way so that i can convert any DOM object into HTML page within the script ?

suppose I have dom object like this: content script.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method == "fromPopup") {
     console.log("got Request from Popup");   
     var myDivObj = document.getElementById("definition");
   //sendResponse({data: "from Content Script to Popup"});
   if ( myDivObj ) {
     sendResponse({data:myDivObj});
     }
     else{
     sendResponse({data:"Empty or No Tag"});
     }
      console.log("sent Response1");   
  } else {
    sendResponse({}); // snub them.
    console.log("sent Response2");   
  }
});

here is my popup.html

<body>
  <Div>Searching..</Div>
  <Div id="output">Response??</Div>
  <script>
  console.log("Pop UP Clicked");
 chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) {

    console.log("got Response from Content Script");   
    document.getElementById("output").innerHTML=response.data;
  });
});
  </script>


</body>

I know we can send onaly JSON type of data to the popup.html page.. am i right ?

If yes is ther any way that I can creat HTML page with DOM Object( myDivObj ) which I collected..

Any alternative solution..?

In short i want get only specific part of the current tab page in DOM object and display it in either popup.html or separate html page..


回答1:


Use sendResponse({data:myDivObj.outerHTML});. This returns the string which can be used to re-construct the HTML.

Notes:

  • Dynamically added event listeners and properties are lost, unless attribute/content-modifying methods are used (setAttribute('key','value') / .innerHTML=...'.
  • The element may look different, because of style sheets.

Warning: Do not blindly inject the code from arbitrary pages. Otherwise, you're opening a security hole in your extension: All scripts in the popup have full access to all permitted extension APIs.



来源:https://stackoverflow.com/questions/11261715/chrome-extension-get-specific-part-of-the-current-tab-page-in-dom-object-and-di

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