Search code examples
javascripthtmljquerygoogle-chrome-extension

Copy Data in DOM Show in Popup.html In (Google Extensions)


I am looking for an onclick inside the Popup.html button, Copy website element data, and set data inside the Popup.html ID which is N/a currently.

enter image description here

manifest.json

{
    "name": "Copy Data in DOM",
    "description": "Extension ",
    "version": "1.0",
    "manifest_version": 3,

    "permissions": ["storage", "activeTab", "scripting"],
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
            "16": "/images/get_started16.png",
            "32": "/images/get_started32.png",
            "48": "/images/get_started48.png",
            "128": "/images/get_started128.png"
        }
    },
    "icons": {
        "16": "/images/get_started16.png",
        "32": "/images/get_started32.png",
        "48": "/images/get_started48.png",
        "128": "/images/get_started128.png"
    }
}

content.js

document.getElementById("copySecondIddata").value;
document.getElementById("copyFirstIddata").value;

popup.html

<html>
<body>
    <p>Fist Id Data: <span id="domFirstIdData">N/a</span></p>
    <p>Fist Id Data: <span id="domSecondIdData">N/a</span></p>

    <button type="button" id="setdata">Seat Data</button>
    <script src="popup.js"></script>
</body>
</html>

popup.js

function idTarget() {
    chrome.tabs.executeScript(null, { file: "content.js" });
};
document.getElementById("setdata").onclick = idTarget;

Solution

  • The last expression in the executed file (or code) is automatically passed to the callback of executeScript.

    content.js: removed

    manifest.json:

    "permissions": ["scripting", "activeTab"]
    

    popup.js:

    document.getElementById('setdata').onclick = async () => {
      try {
        const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
        const res = await chrome.scripting.executeScript({
          target: {tabId: tab.id},
          function: () => [
            document.getElementById('copyFirstIddata').value,
            document.getElementById('copySecondIddata').value,
          ],
        });
        res = res[0].result; // the first element is the main page of the tab
        document.getElementById('domFirstIddata').value = res[0];
        document.getElementById('domSecondIddata').value = res[1];
      } catch (e) {}
    };