2015-03-03 46 views
0

我測試一個在線調查應用程序。我的應用程序中有數百個文本框,爲了測試目的,我必須輸入一些數字。所以我創建了一個Chrome擴展來填充表單。我做到了,幾乎和我預期的一樣 - 除了有一個小問題。默認彈出窗口匹配URL

manifest.json的:

{ 
    "name": "FillForm", 
    "version": "1.0", 
    "manifest_version": 2, 
    "description": "FillForm", 
    "browser_action": { 
    "default_icon": "icon.png", 
    "default_popup": "popup.html" 
    }, 
    "permissions": ["activeTab"] 
} 

每當我點擊browserAction按鈕 - 它打開,那裏是一個文本框的popup.html。如果我在那裏輸入1,它將在我的應用程序中輸入所有文本框的1 - 這是我想要的。

現在我想打開popup.html僅適用於我的應用程序,即匹配URL http://example.com,因爲我不想在任何其他頁面中輸入任何信息。

我該如何做到這一點?

回答

1

我會在與指定的URL匹配的頁面中注入popup.html的內容。

  • 這簡化你的行動來填補你的表格(你沒有必須點擊擴展程序圖標)
  • 它不會有額外的圖標

饜足您的瀏覽器這樣做,第一修改清單:

{ 
    "name": "FillForm", 
    "version": "1.0", 
    "manifest_version": 2, 
    "description": "FillForm", 
    "content_scripts": [ 
    { 
    "matches": ["http://*.xxx.com/*"], // put your URL pattern here 
    "js": ["popup_inject.js"] 
    } 
], 
    "web_accessible_resources": ["popup.html"] 
    "permissions": ["activeTab"] 
}

popup_inject.js

var iframe = document.createElement ("iframe"); 
iframe.src = chrome.extension.getURL ("popup.html"); 
iframe.style.position="absolute"; 
iframe.style.top="10px"; 
iframe.style.right="10px"; 
iframe.style.border="solid 1px #aaa"; 

document.querySelector("body").appendChild(iframe); 
+0

加1的時間和答案。我會檢查並通知你。 – KitKarson 2015-03-03 18:40:38

2

這就是Page Actions的確切目的:提供一個僅在特定網站上可見的按鈕。

首先,你browser_action鍵更改爲page_action

"page_action": { 
    "default_icon": "icon.png", 
    "default_popup": "popup.html" 
    }, 

你需要決定自己的時候表現出來。通過declarativeContent API,您可以提供一套規則說明您何時需要這樣做。

添加declarativeContent權限:

"permissions": ["activeTab", "declarativeContent"] 

然後,添加一個background script將管理規則。由於您不需要後臺腳本始終處於活動狀態,因此非常適合Event Page。現在

"background": { 
    "scripts": ["eventPage.js"], 
    "persistent": false 
    }, 

,活動頁面代碼:

// eventPage.js 

// This only needs to run on install/update, rules are remembered 
chrome.runtime.onInstalled.addListener(function(details) { 
    var rule1 = { 
    conditions: [ 
     new chrome.declarativeContent.PageStateMatcher({ 
     // See declarativeContent docs for more options 
     pageUrl: { hostEquals: 'www.example.com' } 
     }) 
    ], 
    actions: [ new chrome.declarativeContent.ShowPageAction() ] 
    }; 

    // Remove existing rules, if any 
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() { 
    // Then, add our rule1 
    chrome.declarativeContent.onPageChanged.addRules([rule1]); 
    }); 
}); 
+0

加1爲您的時間和答案。我會檢查並通知你。 – KitKarson 2015-03-03 18:40:50