简体   繁体   English

单击时在网页上的注入的侧边栏chrome扩展名的字段内添加所选文本

[英]adding the selected text on the webpage inside a field in an injected sidebar chrome extension when clicked

嗨,我有一个chrome扩展名,单击后会注入一个边栏。我想要的是,如果我在网页上选择一个位置然后单击扩展名,它将自动用所选文本填充位置输入栏并在其中调用Maps API以位置名称作为查询的iframe。

I have seen some problems in the code. 我在代码中看到了一些问题。

Background.js Background.js

var place = window.getSelection().toString() should not be placed here. var place = window.getSelection().toString()不应放在此处。 You can't have selected text in the background page. 您无法在后台页面中选择文本。 You can remove this line. 您可以删除此行。

Like said in comment, You should replace the depracated chrome.tabs.getSelected by chrome.tabs.query({active: true}, callback); 就像在评论中说的那样,您应该用chrome.tabs.query({active: true}, callback);替换已取消使用的chrome.tabs.getSelected chrome.tabs.query({active: true}, callback); , read more about this function here . 在此处阅读有关此功能的更多信息。

Script.js Script.js

The smelling code is the handleRequest function. 气味代码是handleRequest函数。 You have made to condition, the first doing nothing, and the second, if I have well understood, displaying the sidebar. 您已经适应了条件,第一个不执行任何操作,第二个(如果我完全理解的话)显示侧边栏。

So I think the problem is here. 所以我认为问题出在这里。 You should move the place = window.getSelection().toString(); 您应该移动place = window.getSelection().toString(); statement to the first condition and then call sendResponse({data : place}) . 声明到第一个条件,然后调用sendResponse({data : place}) This way, you should send back the text selected in the page to the background script. 这样,您应该将页面中选择的文本发送回后台脚本。

function handleRequest(request, sender, sendResponse)
{
    if (request.method == "getSelection")
    {
       place = window.getSelection().toString();
       console.log("sending to background : " + place);
       sendResponse({data: place});
    }

    if (request.callFunction == "toggleSidebar")
    {
       toggleSidebar();
       console.log("adasda");
    }
}

All code 所有代码

You should do a clean up. 您应该清理一下。 There is lot of not usefull comment that you should remove. 您应该删除许多无用的注释。 It will improve the readability of your code for a better debuging. 它将提高代码的可读性,以进行更好的调试。

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

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