我正在研究一個簡單的Chrome擴展,以隱藏某些頁面上的元素。我一直在黑客找到一些我在網上找到的例子,並且我將它作爲瀏覽器操作工作,需要用戶點擊圖標才能激活它。我正在尋找一種方法來讓它自動運行並隱藏內容。如何在沒有用戶輸入的情況下運行內容更改Chrome擴展程序?
我幾年沒有做太多的編程工作,請原諒這個爛攤子。我正在考慮重新編程,並認爲將幾個擴展放在一起會很有趣。
那麼我在這裏錯過了什麼?我附上了我正在從事的隱藏Pinterest.com網站聊天工作的代碼。
清單
{
"name": "NoPChat",
"version": "1.0.0",
"manifest_version": 2,
"description": "Hide Pinterest Chat",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action" :
{
"default_icon" : "images/icon-19.png",
"default_title" : "Toggle Pinterest chat"
},
"permissions" : [
"declarativeContent",
"activeTab"
],
"content_scripts":
[
{
"matches": ["*://*.pinterest.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}
],
"icons" : {
"48" : "images/icon-48.png",
"128" : "images/icon-128.png"
}
}
content.js
hidePinterestChat();
function hidePinterestChat() {
var el = document.getElementsByClassName("Conversation Module"),
n = el.length;
for (var i = 0; i < n; i++) {
var e = el[i];
e.style.display = 'none';
}
var el2 = document.getElementsByClassName("Module Dropdown PositionModule aboveModal activeConversationDropdown active ui-droppable positionModuleFixed positionFixed defaultCaret positionModuleElement positionRight"),
n = el2.length;
for (var i = 0; i < n; i++) {
var e = el2[i];
e.style.display = 'none';
}
}
background.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's URL contains a 'g' ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'pinterest.com' },
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
});
編輯: 我得到它通過增加content.js
function partA() {
window.setTimeout(hidePinterestChat,5000);
}
partA();
hidePinterestChat();
...
這是到會話氣泡彈出了幾秒鐘,然後消失點超時工作得更好。我相信肯定有更好的辦法。
我刪除了我的答案,因爲我誤解了你的代碼;你通過不將'hidePinterestChat();'格式化爲代碼來犯了一個非常重要的錯字。 – Xan
對不起 - 我不確定格式錯誤在哪裏。 – Skeleton
我已經修好了 - 你在多行代碼之前沒有留下空行。查看編輯歷史記錄。 – Xan