微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 popup.js 脚本中获取网页 HTML - Chrome 扩展

如何解决在 popup.js 脚本中获取网页 HTML - Chrome 扩展

我有一个 popup.html,其中包含一个按钮。单击按钮时,我想检索它所在的当前选项卡的 html,而不是弹出窗口的 html。如果我执行 document.getElementById 或其他类似的函数,我只会得到弹出窗口的 Html。如何重定向它以获取网页的 html。我曾尝试获取当前选项卡 ID 并从中获取 html,但这也不起作用。我还尝试在内容脚本中获取 html 并将其传递给我的 popup.js,但是每次单击我的按钮时我都需要该 html,但 contentscript 只会在启动时运行。我当前的代码

popup.html

<!DOCTYPE html>
<html>
    <script src="popup.js"></script>
    <div id="startupDiv" style="padding: 20px 20px 20px 20px;">           
        <h3>Hello,</h3>
        <p>Please enter your phone number to sign up: </p>         
        <input id="phone_number" />                   
        <button id="start" type="button">START</button>
    </div> 
    <div id="secondDiv">
        <h3>Thanks for signing up</h3>
    </div>
</html> 

popup.js

document.addEventListener('DOMContentLoaded',function () {
    document.getElementById('start').addEventListener('click',startScripts);
});

function startScripts() {
    chrome.storage.sync.get('phone_number',function(data) {
        if (typeof data.phone_number === 'undefined') {
            var phone_number=document.getElementById("phone_number").value;
            console.log(phone_number)
            if (phone_number.length > 0) {
                chrome.storage.sync.set({"phone_number": phone_number},function() {
                    getPrice(phone_number)
                });
            }
        } else {
            getPrice(data.phone_number)
        }
    });
}

function getPrice(phone_number) {
    var currentPrice = document.getElementsByClassName("SinglePriceLarge__PriceRow-ijh2t7-0 dESKpj")[0].getElementsByTagName('span')[0].innerHTML;
    console.log(currentPrice)
}

manifest.json

{
  "manifest_version": 2,"name": "Top Shot Notifications","version": "0.1.0","permissions": [
    "activeTab","tabs","storage"
  ],"content_scripts": [{
    "js": ["contentscript.js"],}],"browser_action": {
    "default_icon": "icon.png","default_popup": "popup.html"
  }
  
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。