从一个chrome扩展如何检查网页元素是否存在或不在页面上?

jgwigjjp  于 2023-02-27  发布在  Go
关注(0)|答案(1)|浏览(180)

我正在尝试建立一个chrome扩展,让我检查一些元素是否出现在打开的页面上。有人能帮我吗?当我使用下面的代码时,它给出了空值。
manifest.json

{
  "name": "A browser action with a popup that changes the page color.",
  "version": "1.0",
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "browser_action": {
      "default_title": "Set this page's color.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "manifest_version": 2
}

popup.html

<!doctype html>
<html>
  <head>
    <script src="jquery.js"></script>
    <script src="popup.js"></script>
  </head>
</html>

popup.js

if(jQuery('#nav').is(':visible')==true){
    alert("true");
}else {
        alert("false");
}
zbsbpyhn

zbsbpyhn1#

您必须使用"内容脚本",它将在您指定的页面上运行。只有当用户单击您的扩展按钮时,才会调用弹出页面。

{
    ...,
    "content_scripts": [
        {
            "matches": [
                "*"
            ],
            "js": [
                "script.js"
            ]
        }
    ],
    ...
}

更多信息:http://developer.chrome.com/extensions/content_scripts.html
此外,检查时,首先检查元素是否实际存在,然后检查其可见性:

var $nav = jQuery('#nav');

if ($nav.length > 0 && $nav.is(':visible') == true) {
    alert("true");
} else {
    alert("false");
}

相关问题