在 DOM 中复制数据显示在 Popup.html 中(Google 扩展程序)

时间:2021-04-22 08:42:32

标签: javascript html jquery google-chrome-extension

我正在寻找 Popup.html 按钮内的 onclick,复制网站元素数据,并在当前为 N/a 的 Popup.html ID 内设置数据。

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;

1 个答案:

答案 0 :(得分:0)

执行的文件(或代码)中的最后一个表达式会自动传递给executeScript的回调。

content.js:已删除

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) {}
};
相关问题