chrome扩展实现跨域通信示例
chrome扩展实现2个不同域名跨域通信示例,以下代码通过向百度搜索页面中插入iframe加载本网站页面,然后实现相互发送信息(当然可以在对应页面实现dom的操作,示例仅输出相互发送的信息),效果如下

chrome扩展开启开发者模式后可以直接加载扩展程序
manifest.json
{
"name": "测试",
"manifest_version": 2,
"version": "1.0",
"author":"showbo,http://www.w3dev.cn",
"description": "测试",
"content_scripts": [{"matches": ["*://*/*"],"js": ["baidu.js"]}],
"permissions": ["*://*/*","tabs"]
}
baidu.js
if(location.hostname=='www.baidu.com')//在百度上插入通信的测试 iframe
window.addEventListener('load', function () {
var div = this.document.createElement('div')
var ifr = document.createElement('iframe');
ifr.src = 'https://www.w3dev.cn/postmessage.html';
div.appendChild(ifr);
var btn = document.createElement('input');
btn.type = 'button';
btn.value = '发信息给w3dev.cn'
div.appendChild(btn);
btn.onclick = function () {
ifr.contentWindow.postMessage("www.baidu.com-->www.w3dev.cn:" + new Date().toLocaleString(),
"https://www.w3dev.cn");
}
document.body.insertAdjacentElement('afterBegin', div);
window.addEventListener('message', function (e) {
//需要的dom操作
alert(`来自${e.origin}的信息
${JSON.stringify(e.data)}
`);
document.getElementById('kw').value=e.data
}, false);
})
本网站测试页面postmessage.html源代码
<input type="button" value="向百度发送信息" onclick="setKeyword()"/>
<script>
var fromBD = document.getElementById('fromBD');
function setKeyword() {
parent.postMessage("www.w3dev.cn-->www.baidu.com:" + new Date().toLocaleString(),
"https://www.baidu.com");
}
window.addEventListener('message', function (e) {
alert(`来自${e.origin}的信息
${JSON.stringify(e.data)}
`)
}, false);
</script>
加支付宝好友偷能量挖...

原创文章,转载请注明出处:chrome扩展实现跨域通信示例
