7

我正在寻找一个网页内的功能te激活一个Chrome扩展。从网站调用Chrome扩展的后台功能

试想一下,http://www.example.com/test.html包含:

<script> 
hello(); 
</script> 

而且我的背景页面包含hello函数的定义:

function hello() { 
    alert("test"); 
} 

我怎样才能确保Chrome扩展的背景页的hello被调用时test.html来电hello();

+0

不,你CA不是出于明显的安全原因。该扩展需要公开其API的目的 – Bergi

回答

1

不,你上面的代码,因为background page(s) architecture

是与content scripts

示范使用内容脚本

的manifest.json

注册内容脚本myscripts。 js

{ 
"name": "NFC", 
"description": "NFC Liken", 
"version": "0.1", 
"manifest_version": 2, 
"permissions": ["tabs", "http://*/", "https://*/"], 
"content_scripts": { 
    "matches": "http://www.example.com/*", 
    "js": [ "myscript.js"] 
    }, 
"browser_action": { 
"default_icon": "sync-icon.png", 
"default_title": "I Like I Tag" 
} 
} 

让我知道你是否需要更多信息。

+0

谢谢你的答案。但是没有交易..我也可以在myscript.js中使用这些函数。 函数clearhist(){ var millisecondsPerWeek = 1000 * 60 * 60 * 24 * 7; var oneWeekAgo =(new Date())。getTime() - millisecondsPerWeek; chrome.browsingData.remove({ “因为”:oneWeekAgo },{ “应用程序缓存”:真实, “缓存”:真实, “曲奇”:真实, “下载”:真实, “文件系统” :真, “FORMDATA”:真实, “历史”:真实, “IndexedDB的”:真实, “的localStorage”:真实, “pluginData”:真实, “密码”:真实, “的WebSQL”:回调); true },callback); } –

+0

@WoutervanReeven:不能,你不能直接在myscript.js中放置这段代码,但是你可以通过在'background'页面中通过消息通信来间接调用代码来实现。参考[这](http://stackoverflow.com/questions/13637715/not-receiving-any-data-from-webpage-to-content-js-of-chrome-extension/13638508#13638508)让我知道,如果你需要更多的信息 – Sudarshan

+0

所以我需要在后台js脚本中调用javascript函数。在页面http://www.example.com/test.html的html中做些事情来调用Chrome扩展中的脚本。 背景HTML myscript.js 你好(); –

9

网页是能够调用后台页面的功能之前,需要以下亟待解决的问题:

  1. 能够使用hello();从网页。这是通过使用内容脚本定义hello的脚本injecting完成的。注入函数使用自定义事件或postMessage与内容脚本进行通信。
  2. 内容脚本需要与背景进行通信。这是通过chrome.runtime.sendMessage实现的。
    如果网页需要得到回复,以及:
  3. 发送从背景页的答复(sendMessage/onMessage,见下文)。
  4. 在内容脚本中,创建自定义事件或使用postMessage向网页发送消息。
  5. 在网页中处理此消息。

所有这些方法都是异步的,必须通过回调函数来实现。

这些步骤需要仔细设计。这是一个实现上述所有步骤的通用实现。您需要了解的实现:

  • 在要注入代码中,每当需要联系内容脚本时,请使用sendMessage方法。
    用法:sendMessage(<mixed message> [, <function callback>])

contentscript.js

// Random unique name, to be used to minimize conflicts: 
var EVENT_FROM_PAGE = '__rw_chrome_ext_' + new Date().getTime(); 
var EVENT_REPLY = '__rw_chrome_ext_reply_' + new Date().getTime(); 

var s = document.createElement('script'); 
s.textContent = '(' + function(send_event_name, reply_event_name) { 
    // NOTE: This function is serialized and runs in the page's context 
    // Begin of the page's functionality 
    window.hello = function(string) { 
     sendMessage({ 
      type: 'sayhello', 
      data: string 
     }, function(response) { 
      alert('Background said: ' + response); 
     }); 
    }; 

    // End of your logic, begin of messaging implementation: 
    function sendMessage(message, callback) { 
     var transporter = document.createElement('dummy'); 
     // Handles reply: 
     transporter.addEventListener(reply_event_name, function(event) { 
      var result = this.getAttribute('result'); 
      if (this.parentNode) this.parentNode.removeChild(this); 
      // After having cleaned up, send callback if needed: 
      if (typeof callback == 'function') { 
       result = JSON.parse(result); 
       callback(result); 
      } 
     }); 
     // Functionality to notify content script 
     var event = document.createEvent('Events'); 
     event.initEvent(send_event_name, true, false); 
     transporter.setAttribute('data', JSON.stringify(message)); 
     (document.body||document.documentElement).appendChild(transporter); 
     transporter.dispatchEvent(event); 
    } 
} + ')(' + JSON.stringify(/*string*/EVENT_FROM_PAGE) + ', ' + 
      JSON.stringify(/*string*/EVENT_REPLY) + ');'; 
document.documentElement.appendChild(s); 
s.parentNode.removeChild(s); 


// Handle messages from/to page: 
document.addEventListener(EVENT_FROM_PAGE, function(e) { 
    var transporter = e.target; 
    if (transporter) { 
     var request = JSON.parse(transporter.getAttribute('data')); 
     // Example of handling: Send message to background and await reply 
     chrome.runtime.sendMessage({ 
      type: 'page', 
      request: request 
     }, function(data) { 
      // Received message from background, pass to page 
      var event = document.createEvent('Events'); 
      event.initEvent(EVENT_REPLY, false, false); 
      transporter.setAttribute('result', JSON.stringify(data)); 
      transporter.dispatchEvent(event); 
     }); 
    } 
}); 

background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { 
    if (message && message.type == 'page') { 
     var page_message = message.message; 
     // Simple example: Get data from extension's local storage 
     var result = localStorage.getItem('whatever'); 
     // Reply result to content script 
     sendResponse(result); 
    } 
}); 

Chrome扩展程序,是不是不完整的清单文件,所以这里的manifest.json文件,我用测试答案:

{ 
    "name": "Page to background and back again", 
    "version": "1", 
    "manifest_version": 2, 
    "background": { 
     "scripts": ["background.js"] 
    }, 
    "content_scripts": [{ 
     "matches": ["http://jsfiddle.net/jRaPj/show/*"], 
     "js": ["contentscript.js"], 
     "all_frames": true, 
     "run_at": "document_start" 
    }] 
} 

此扩展已在http://jsfiddle.net/jRaPj/show/(包含hello();,如问题中所示)进行测试,并显示一个对话框,指出“Background说:null”。
打开后台页面,使用localStorage.setItem('whatever', 'Hello!');查看消息是否正确更改。

+0

@Xan'chrome.extension.sendMessage'是'chrome.runtime.sendMessage'的别名。你可能与'chrome.extension.sendRequest'混淆? –

+0

我并不困惑;但该功能已完全退役(文档中未提及),但由于延续旧样本代码而不断弹出新代码。请参阅[此问题](https://code.google.com/p/chromium/issues/detail?id=495052)将其标记为已弃用。 – Xan

0

有一个内置的解决方案Send messages from web pages到扩展

mainfest.json

"externally_connectable": { 
    "matches": ["*://*.example.com/*"] 
} 

网页:

// The ID of the extension we want to talk to. 
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc"; 

// Make a simple request: 
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url}, 
    function(response) { 
    if (!response.success) 
     handleError(url); 
    }); 

扩展的背景脚本:

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) { 
    if (sender.url == blacklistedWebsite) 
     return; // don't allow this web page access 
    if (request.openUrlInEditor) 
     openUrl(request.openUrlInEditor); 
    }); 
相关问题