【问题标题】:Injected HTML accessing the Chrome API and global variables注入的 HTML 访问 Chrome API 和全局变量
【发布时间】:2013-03-30 15:46:08
【问题描述】:

我正在开发一个 Chrome 扩展程序,而且我是这个过程的新手。我正在开发的扩展程序将 HTML 侧边栏注入页面,将 java-script 函数注入到标题中,然后让用户按下侧边栏上的按钮来创建/保存我的扩展程序的数据。

但是,当我想保存信息时,我使用 localStorage,但是,localStorage 总是相对于当前网站保存。我如何使用 localStorage 来保存我们的扩展程序?

此外,我想在 chrome 扩展中使用一些全局 javascript 变量。这些属于哪里?我知道我目前无法从注入的 Javascript 访问它们。

我研究了消息传递,但遇到了一些问题。我不确定它在将 javascript 注入页面标题的范围内是如何工作的。我已尝试使用此示例,但我的扩展程序似乎没有捕捉到该消息。

// This function is called in the injected header javascript.
function sendToExtension() {
    setTimeout(function() {
    console.log('page javascript sending message');
    window.postMessage({ type: 'page_js_type',
        text: "Hello from the page's javascript!"},
        '*' /* targetOrigin: any */);
    }, 10);
}

// This is installed in a background script.
window.addEventListener('message', function(event) {
    console.log('content_script.js got message:', event);
});

【问题讨论】:

  • 提示:使用chrome.storage 而不是localStorage。由于 postMessage 已经是异步的,因此更改代码可能不会有任何问题。
  • 嗯,我会更多地研究这个,因为它看起来像一个有用的 API - 但我仍然遇到注入的 HTML 无法访问 chrome API 的问题。
  • 您在答案中提出了正确的解决方案:使用postMessageonmessage

标签: javascript google-chrome google-chrome-extension local-storage html-injections


【解决方案1】:

你必须使用 Chrome 的 sendMessage 函数和 onMessage 监听器。见下文:

function sendToExtension() {
    console.log('Sending message');
    chrome.runtime.sendMessage({ext: "myExtension"}, function(response) {
      console.log(response.ack);
    });
}

// Listener - Put this in the background script to listen to all the events.
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ext) {
        console.log('Message received from ' + request.ext);
        sendResponse({ack:'received'}); // This send a response message to the requestor
    }
});

【讨论】:

  • 这几乎是我要找的,但是“sendToExtension”是从注入的 HTML 脚本中调用的。从那里,我无法访问“chrome.runtime.sendMessage”API。
  • 我最终做的是从窗口传递到内容脚本,然后从内容脚本传递到后台脚本。
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 2018-10-28
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2012-07-21
相关资源
最近更新 更多