jjzjj

javascript - chrome.runtime.sendMessage 在 Chrome 扩展程序中不起作用

coder 2024-07-20 原文

我正在尝试创建一个新的扩展。不久前我能够使用 chrome.runtime.sendMessage 函数,但现在,我已经尝试了所有方法,但它仍然无法将消息发送到后台脚本。控制台正在填充来自 content-script.js 但不是来自 background.js

的日志消息

content-script.js

console.log("Hello World!s");
$(document).ready(function() {
    console.log("DOM READY!");
    $(document.documentElement).keydown(function (e) {
        console.log("Key Has Been Pressed!");
        chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
                if (response.fileData) {
                    alert("Contents Of Text File = ");
                }
                else {
                    console.log("No Response Received");
                }
            })

    })
});

background.js

console.log("Atleast reached background.js")
        chrome.runtime.onMessage.addListener (
            function (request, sender, sendResponse) {
                console.log("Reached Background.js");
                if (request.Message == "getTextFile") {
                    console.log("Entered IF Block");
                        $.get("http://localhost:8000/quicklyusercannedspeechbucket/helloWorld1", function(response) {
                    console.log(response);
                    sendResponse({fileData: response})
                })
            }
            else {
                console.log("Did not receive the response!!!")
            }
        }
    );

list .json

{
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.1",
  "content_scripts": [ {
    "all_frames": true,
    "js": [ "jquery-2.1.4.min.js", "content-script.js" ],
    "matches": [ "http://*/*", "https://*/*", "file://*/*" ]
  } ],
  "permissions": [ "http://*/*", "https://*/*", "storage" ],
  "background": {
    "scripts": [
      "jquery-2.1.4.min.js",
      "background.js"
    ]
  }
}

感谢任何帮助:)

谢谢!

最佳答案

您需要更改您的代码,以便在 background.js 中您必须更改行为:

console.log("Atleast reached background.js")
chrome.runtime.onMessage.addListener (
    function (request, sender, sendResponse) {
        console.log("Reached Background.js");
        if (request.Message == "getTextFile") {
            console.log("Entered IF Block");
            $.get("http://localhost:63342/Projects/StackOverflow/ChromeEXT/helloWorld1", function(response) {
                console.log(response);

                // to send back your response  to the current tab
                chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                    chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
                        ;
                    });
                });


            })
        }
        else {
            console.log("Did not receive the response!!!")
        }
    }
);

对于 contentscript 你需要做的:

console.log("Hello World!s");
$(document).ready(function() {
    console.log("DOM READY!");
    $(document.documentElement).keydown(function (e) {
        console.log("Key Has Been Pressed!");
        chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
            ;
        })

    })
});


// accept messages from background
chrome.runtime.onMessage.addListener (function (request, sender, sendResponse) {
    alert("Contents Of Text File = " + request.fileData);
});

sendResponse 可以用作即时反馈,而不是计算结果。

关于javascript - chrome.runtime.sendMessage 在 Chrome 扩展程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34550886/

有关javascript - chrome.runtime.sendMessage 在 Chrome 扩展程序中不起作用的更多相关文章

  1. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  2. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  3. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  4. c - mkmf 在编译 C 扩展时忽略子文件夹中的文件 - 2

    我想这样组织C源代码:+/||___+ext||||___+native_extension||||___+lib||||||___(Sourcefilesarekeptinhere-maycontainsub-folders)||||___native_extension.c||___native_extension.h||___extconf.rb||___+lib||||___(Rubysourcecode)||___Rakefile我无法使此设置与mkmf一起正常工作。native_extension/lib中的文件(包含在native_extension.c中)将被完全忽略。

  5. ruby-on-rails - 向 Rails 3 添加 Ruby 扩展方法的最佳实践? - 2

    我有一个要在我的Rails3项目中使用的数组扩展方法。它应该住在哪里?我有一个应用程序/类,我最初把它放在(array_extensions.rb)中,在我的config/application.rb中我加载路径:config.autoload_paths+=%W(#{Rails.root}/应用程序/类)。但是,当我转到railsconsole时,未加载扩展。是否有一个预定义的位置可以放置我的Rails3扩展方法?或者,一种预先定义的方式来添加它们?我知道Rails有自己的数组扩展方法。我应该将我的添加到active_support/core_ext/array/conversion

  6. ruby-on-rails - "assigns"在 Ruby on Rails 中有什么作用? - 2

    我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o

  7. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  8. ruby - 下载位置 Selenium-webdriver Cucumber Chrome - 2

    我将Cucumber与Ruby结合使用。通过Selenium-Webdriver在Chrome中运行测试时,我想将下载位置更改为测试文件夹而不是用户下载文件夹。我当前的chrome驱动程序是这样设置的:Capybara.default_driver=:seleniumCapybara.register_driver:seleniumdo|app|Capybara::Selenium::Driver.new(app,:browser=>:chrome,desired_capabilities:{'chromeOptions'=>{'args'=>%w{window-size=1920,1

  9. ruby - 如何在 ruby​​ 中复制目录结构,不包括某些文件扩展名 - 2

    我想编写一个ruby​​脚本来递归复制目录结构,但排除某些文件类型。因此,给定以下目录结构:folder1folder2file1.txtfile2.txtfile3.csfile4.htmlfolder2folder3file4.dll我想复制这个结构,但不包含.txt和.cs文件。因此,生成的目录结构应如下所示:folder1folder2file4.htmlfolder2folder3file4.dll 最佳答案 您可以使用查找模块。这是一个代码片段:require"find"ignored_extensions=[".cs"

  10. ruby - 扩展类和实例 - 2

    这个问题有两个部分。在RubyProgrammingLanguage一书中,有一个使用模块扩展字符串对象和类的示例(第8.1.1节)。第一个问题。为什么如果您使用新方法扩展类,然后创建该类的对象/实例,则无法访问该方法?irb(main):001:0>moduleGreeter;defciao;"Ciao!";end;end=>nilirb(main):002:0>String.extend(Greeter)=>Stringirb(main):003:0>String.ciao=>"Ciao!"irb(main):004:0>x="foobar"=>"foobar"irb(main):

随机推荐