2015-03-02 62 views
0

我必須在訪問過的網頁(我知道存在)上調用javascript函數,從Chrome擴展的browser_action圖標點擊?從Chrome擴展的頁面上調用瀏覽功能圖標點擊

我已經通過相關頁面調用函數的幾種答案閱讀,但不知道我見過的任何可從點擊圖標來調用。

browser_action點擊通過background.js的事件處理chrome.browserAction.onClicked.addListener處理。從那裏我通過sendMessage調用內容腳本函數。然而,在內容腳本中,我無法訪問調用頁面函數,儘管DOM可能是可訪問的。

的manifest.json

{ 
    "manifest_version": 2, 

    "name": "Page Inspector", 
    "description": "blah", 
    "version": "1.0", 
    "browser_action": { 
    "default_icon": "img/icon.png", 
    "name": "Click to Inspect" 
    }, 
    "permissions": [ 
    "tabs", 
    "http://*/*", 
    "https://*/*" 
    ], 
    "background": { 
    "scripts": ["background.js"] 
    }, 
    "content_scripts": [ 
    { 
     "matches": [ "https://MYURL/*" ], 
     "js": [ "content.js" ] 
    } 
    ], 
    "web_accessible_resources": [ 
    "inspector.js" 
    ] 
} 

background.js

logOnSuccess = function() { 
    console.log("inspected successfully"); 
} 

chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON 
    console.log(document.title); 
    /*...check the URL of the active tab against our pattern and... */ 
    if (tab.url.indexOf("/MYURL") != -1) { // Inspect whether the place where user clicked matches with our list of URL 
    /* ...if it matches, send a message specifying a callback too */ 
    chrome.tabs.sendMessage(tab.id, { text: "inspect" }, logOnSuccess); 
    } 
}); 

content.js

// inject the main inspector.js script in to the page 
var scriptEl = document.createElement('script'); 
scriptEl.src = chrome.extension.getURL('inspector.js'); 
scriptEl.addEventListener('load', null, false); 
document.head.appendChild(scriptEl); 

/* Listen for messages */ 
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { 
    /* If the received message has the expected format... */ 
    if (msg.text && (msg.text == "inspect")) { 
    /* Call the specified callback, passing 
     the web-pages DOM content as argument */ 
    //alert("From Inpector : " + document.title); 
    window.inspectPage(); 
    } 
}); 

個inspector.js

window.inspectPage = function() { 
$("input[FieldName='FIRSTNAME']").css("background-color", "lightblue"); 
    } 

所以當圖標按鈕從backgroud.js點擊我希望能夠調用inspectPage函數在頁面上(因爲它是在注入到訪問網頁)。通過上面的代碼,我得到一個運行時錯誤 - inspectPage是未定義的。

無論如何解決這個問題?

回答

1

你是對的,它無法在網頁上調用JavaScript函數,但是您可以在DOM中連接網頁。 (如果是您的網頁,您可以使用chrome.runtime函數在擴展和網頁之間發送消息)。

相關問題