从web_accessible_resource到内容脚本的window.postMessage [英] window.postMessage from web_accessible_resource to content script

查看:129
本文介绍了从web_accessible_resource到内容脚本的window.postMessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将来自web_accessible_resource的消息发布到我的chrome扩展程序的内容脚本中.

i try to post a message from a web_accessible_resource to a content-script of my chrome extension.

我的manifest.json部分:

"content_scripts": [{
  "matches": ["http://*/*"],
  "js": ["content.js"]
}],
"web_accessible_resources": ["run.js"]

content.js

// this listener is never triggered ;-(
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
  if (request.type === 'foo') {
    // do whatever i want if request.type is foo       
  }
});

run.js

window.postMessage({type: 'foo'}, '*');

我也试过了的方法:

直接在run.js中添加侦听器:

window.addEventListener("message", function(msg) {
  if (msg.data.type === 'foo') {
    // that one works
  }
});

通过后台脚本发布消息:

chrome.tabs.getCurrent(function (tab) {
  chrome.tabs.sendMessage(tab.id, {type: "foo"});
});

问题:

我该怎么办?我需要为我的内容脚本设置一些授权或其他内容吗,或者为什么这不起作用?

Question:

What do i have to do? do i need to set some authorisation or something for my content-script or why does this not work???

推荐答案

您现在可以启用api,将消息直接从网页发送到您的扩展程序ID

You can now enable the api to send messages directly from a webpage to your extension id

在清单中启用

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

从网页发送消息:

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

接收扩展名:

chrome.runtime.onMessageExternal.addListener(function(){});

请参阅: https://developer.chrome.com/extensions/messaging#external-网页

这篇关于从web_accessible_resource到内容脚本的window.postMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆