简体   繁体   English

Chrome扩展程序和内容脚本只能以“检查弹出窗口”模式进行通信

[英]Chrome extension and content scripts can communicate only in “inspect popup” mode

I have this rather simple extention and content script: 我有这个相当简单的扩展和内容脚本:

manifest.json: manifest.json的:

{
  "name": "My.First.App.Uses.Native.Api",
  "version": "1.0",
  "manifest_version": 2,
  "description": "My app uses my first Native Api",
  "icons": {
    "128": "icon-128__2.png"
  },
  "permissions": [
    "nativeMessaging", "activeTab"
  ],
  "browser_action": {"default_popup": "ext-page.htm"},
  "content_scripts": [
    {
      "matches": ["file:///*"],
      "js": ["content-script.js"]
    }
  ]
}

ext-script.js: EXT-的script.js:

// Listen for messages that come from the client script.
chrome.runtime.onMessage.addListener(
  function( request, sender, sendResponse ) {
    if( request.greeting ) {
        //connectToNative();
        sendResponse( { farewell: request.greeting + ' -> received' } );
    }
  } );

content-script.js: 内容的script.js:

var btn = document.getElementById( 'mybutton' );
if( btn ) {
    btn.addEventListener( 'click', function() {
        var msg = document.getElementById( 'mytext' ).value;
        if( msg ) {
            chrome.runtime.sendMessage( { greeting: msg }, function( response ) {
                console.log( response.farewell );
            } );
            //port.postMessage({joke: "Knock knock"});
        }
        else {
            alert( "content script could not send message" );
        }
    } );
}

ext-page.htm: EXT-page.htm:

<!DOCTYPE html>
<html>
<head>
    <script src='./ext-script.js'></script>
</head>
<body>
    This is a test Extention.
</body>
</html>

A sample page which the content script is injected in : 注入内容脚本的示例页面:

<html>
<head>
    <title>Connecting to a Chrome Extention using Content Script</title>
</head>

<body>
    <p>
        <!--<input id="btn" type="button" value="open document" />-->
        <input id="mytext" type="text" />
        <input id="mybutton" name="mybutton" type="button" value="open document" />
    </p>
</body>
</html>

My problem: If I select the extention and "inspect popup" it (meaning start the debug mode), and click mybutton button on my sample page, then I receive a message back from the extension and I can see it in my page's console. 我的问题:如果我选择扩展并“检查弹出”它(意味着启动调试模式),然后单击我的示例页面上的mybutton按钮,然后我从扩展中收到一条消息,我可以在我的页面控制台中看到它。 What I want is to get that message simply right after clicking that button in my sample page-- of course without debugging the extension. 我想要的是在我的示例页面中单击该按钮后立即获取该消息 - 当然不需要调试扩展。 If I do not "inspect popup" the extension, then I receive this error message: 如果我没有“检查弹出”扩展名,那么我收到此错误消息:

Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined (未知)事件处理程序出错:TypeError:无法读取undefined属性'告别'

Thanks! 谢谢!

I think because you're executing your alert inside main.js which is inside your popup, the popup needs to be open. 我想因为你在弹出窗口内的main.js中执行警报,弹出窗口需要打开。 Try inserting your alert inside background.js. 尝试在background.js中插入警报。 Because background.js gets inserted into your sample page as a content_script, the alert should show up right in your sample page. 因为background.js作为content_script插入到您的示例页面中,所以警报应该显示在您的示例页面中。

Instead of in background.js 而不是在background.js

    if( msg ) {
        chrome.extension.sendRequest( msg );
    }

Do

var msg = document.getElementById( 'mytext' ).value;
    if( msg ) {
        alert( msg );
    }

The docs suggest to have a manifest like this: 文档建议有这样的清单:

{
    "manifest_version": 2,
    "name": "Test",
    "version": "0.1",
    "background": {
    "scripts": ["background.js"],
    //this script is the main one which your extension communicates with
    "persistent": false
},
"browser_action": {
    "default_title": "BET",
    "default_popup": "popup.html"
    //this html file is the one that will be shown when clicked on your extension icon
},
"content_scripts": [{
    //this file will get injected into the tabs
    "matches": ["file:///*"],
    "js": ["content.js"]
}],
"permissions": [
    "tabs",
    "<all_urls>"
]

} }

So inside your content.js your should have 所以在你的content.js中你应该有

chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
});

And inside background.js you receive the message 在background.js里面你会收到消息

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request.greeting);
    if (request.greeting == "hello")
        sendResponse({farewell: "goodbye"});
});

Doing it this way, you will be able to log what you sent from your injected script to your extension...just open the background console from the extensions page. 这样做,您将能够将从注入的脚本发送的内容记录到您的扩展中...只需从扩展页面打开后台控制台即可。

Hope this will help if you change the structure around a little. 希望如果你稍微改变结构,这将有所帮助。 Let me know if it helps 如果有帮助,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM