简体   繁体   English

从chrome扩展名写入网页的文本字段

[英]Writing to a webpage's textfield from chrome extension

I want to create a chrome extension that takes in some text, then opens a website, and tries to write that text to the textfield. 我想创建一个带有一些文本的chrome扩展,然后打开一个网站,并尝试将该文本写入文本字段。 This is what I have: 这就是我所拥有的:

chrome.omnibox.onInputEntered.addListener(
  function(text) {
    chrome.tabs.create({url:"http://www.editpad.org/"});
    document.getElementById("text").value = txt; //.innerHTML = txt
    alert('You just typed "' + text + '"');
  });

I got the ID from just inspecting the element. 我从检查元素中获得了ID。 What do I need to do so it writes? 我需要做什么才能写出来?

Your code runs in the context of the (invisible) background or event page . 您的代码在(不可见) 背景事件页面的上下文中运行。 In order to "switch" to the execution context of the page you've just opened, you need to use a content script (programatically, "on the fly", using chrome.tabs.executeScript ). 为了“切换”到刚刚打开的页面的执行上下文,您需要使用内容脚本 (以编程方式,“动态”,使用chrome.tabs.executeScript )。

The annotated code below shows how to achieve the result you want. 下面带注释的代码显示了如何实现您想要的结果。

chrome.omnibox.onInputEntered.addListener(function(text) {
    chrome.tabs.create({
        url: 'http://www.editpad.org/'
    }, function(tab) {
        // chrome.tabs.executeScript takes a string that will be parsed and run
        // as JavaScript code. To pass a string, you need to make sure that it
        // does not contain any invalid characters. This can easily be achieved
        // by serializing the input string to JSON.
        var serializedValue = JSON.stringify(text);

        chrome.tabs.executeScript(tab.id, {
            code: 'document.getElementById("text").value = ' + serializedValue,
        }, function(result) {
            if (!result) {
                // This usually happens when you do not have the permission to
                // run code in the page. Add the site to the "permissions" 
                // section manifest.json.
                alert('Failed to run content script.\n' +
                    chrome.runtime.lastError.message);
                return;
            }
            // The value of the last expression is passed to the callback of
            // chrome.tabs.executeScript, for each frame. The code runs only in
            // the top-level frame (because `allFrames: true` is not specified),
            // so the result is an array with only one element.
            alert('You just typed: "' + result[0] + '"');
        });
    });
});

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

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