是否可以在不重新加载的情况下运行注入的脚本

Is it possible to run the injected script without reload?

本文关键字:加载 情况下 运行 脚本 注入 新加载 是否      更新时间:2023-09-26

我做了一个简单的自动表单填充器,将创建的html中的信息发送到后台,然后发送内容脚本,这样注入的脚本就可以更改表单上的信息。

我知道内容脚本会在页面加载后运行。我想知道我是否可以再次运行内容脚本,而无需重新加载页面。

我在内容脚本中获得了sendRequest函数,我用它来确保它只在页面准备好时获得信息。然后它将信息添加到表格中,等待我发送。

在内容脚本中,我添加了一个onRequest,它可以工作(它可以获取信息)。但是,我看不到表单上的更改,除非我正在重新编码页面。

我想知道这是否可行,如果可行,我应该学习哪些科目来实现这一点。

我是chrome extensions的新手,我仍在学习:)在其中的一页中,我使用了jQuery,所以用jQuery回答也很好。

我发现,如果我们从背景创建chrome.tabs.sendRequest,我们可以使用内容脚本中的chrome.extestion.onRequest,它每次都会执行,因为它们几乎都在同一时间运行。

所以我在背景中这样做:

  chrome.tabs.query({}, function (tabs) {
        for (var i = 0; i < tabs.length; i++) {
            chrome.tabs.sendRequest(tabs[i].id, {...requests u want to send  }, function (response) {
            });
        }
    });

来自内容脚本

chrome.extension.onRequest.addListener(function (request, sender, sendRespons) {
      //get requested info here
      //call functions.
      sendResponse({}); //send info back to background page.
});

表单的目标可以是避免页面重载的iframe。不确定它有多有用。

再次执行内容脚本的正确方法是使用chrome.tabs.executeScript方法。它接收两个自变量。第一个参数是tabId,它可以通过多种方式获得,例如chrome.tabs事件之一。使用null在当前选择的选项卡中执行内容脚本(注意:这可能也是一个活动的开发工具窗口!)。

示例:

// Reloads the current tab
chrome.tabs.executeScript(null, {code:'location.reload();'});
// Executes contentscript.js in the current tab
chrome.tabs.executeScript(null, {file:'contentscript.js'});
// Executes contentscript.js in all frames in the current tab
chrome.tabs.executeScript(null, {file:'contentscript.js', allFrames: true});
// Receives message from content script, and execute a content script:
chrome.extension.onMessage.addListener(function(details) {
    if (details.message === 'load a content script') {
        chrome.tabs.executeScript(details.sender.tab.id, {file: 'a_script.js'});
    }
});
     // The previous one is activated from a content script, as follows:
     chrome.extension.sendMessage('load a content script');

(由于Chrome 20,必须使用onMessagesendMessage来代替onRequestsendRequest