簡體   English   中英

如何通過將偵聽器添加到“窗口”來從Chrome擴展程序單擊網頁上的按鈕?

[英]How to click a button on a webpage from Chrome extension by adding a listener to `window`?

我正在編寫一個簡單的Chrome擴展程序,它將在我公司內部網站內單擊一個按鈕。 具體而言,該網站包含一個“顯示更多”按鈕,單擊該按鈕將顯示更多數據。

我的問題是,當我執行單擊Chrome控制台中的按鈕所需的Javascript時,一切正常。 但是,當我從擴展的content.js腳本執行它時,未單擊按鈕。

這是我的manifest.json:

{
 "manifest_version": 2,
 "name": "asd",
 "description": "qwe",
 "version": "0.1",
 "author": "abc",
 "browser_action": {
   "default_icon": "asd.png",
   "default_title": "Have a good day",
   "default_title": "asd"
},
"permissions": ["activeTab", "https://ajax.googleapis.com/"],
"content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames": true
    }
  ]
}

content.js是這樣的:

window.addEventListener('load', function(event) {
    console.log("page load!");
    console.log(window.location.href);
    console.log()
    var pageURL = window.location.href;
    if (pageURL.indexOf('example.com')) {
        console.log('example.com');
        var metaTags = document.querySelectorAll('meta');
        for (var i = 0; i < metaTags.length; i++) {
            console.log(metaTags[i].getAttribute('content'));

            if (metaTags[i].getAttribute('name') === 'application-name' && metaTags[i].getAttribute('content') === 'XYZ') {
                console.log('got match');
                var buttonClass = document.getElementsByClassName('source-viewer-more-code');
                console.log('buttonClass = ' +  JSON.stringify(buttonClass));
                var button = buttonClass[0];
                console.log("button = " + button);
            }
        }
    }
});

我確實看到了所有console.log打印,但是JSON.stringify(buttonClass)打印了一個空對象, console.log("buttonw = " + button); 打印未定義。

我目前正在本地運行擴展程序。 這是Chrome權限問題還是其他原因?

如果您可以讀取元標記,我想這不是權限問題,當嘗試通過“ getElementsByClassName”獲取按鈕時,請確保Button位於DOM中(按鈕不在DOM中的一個可能原因是頁面中的一些js ajax請求后,可能會將按鈕填充到DOM)。 (當您在控制台中執行時,您可能會在DOM中填充元素之后執行),如果您希望有一個按鈕但不在dom中,請使用setTimeout之類的內容,然后等待該按鈕由頁面中的其他js填充。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM