【问题标题】:How can I get the current Crome URL?如何获取当前的 Chrome URL?
【发布时间】:2021-08-02 19:37:03
【问题描述】:

我正在 C# 上编写 Windows 窗体应用程序,并尝试在此应用程序中从 Chrome 获取当前 URL。我找到了活动进程,如果它的名称是“chrome”,我会尝试任何方法,但都没有成功。我发现的所有解决方案仅适用于以前版本的 Chrome。据我了解,最好使用谷歌浏览器扩展(但我​​从来没有写过它们,而且我对 JS 很熟悉)。

所以,我试着写一个扩展:

manifest.js:

{
"manifest_version": 3,
"name": "URL collector",
"version": "0.11",
"description": "Собирает URL посещенных ресурсов",
"permissions": [
    "tabs",
    "activeTab",
    "webNavigation",
    "scripting"
],
"background": {
    "service_worker": "background.js"
  },
"content_scripts": [
    {
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": [
            "app.js"
        ]
    }
]}

background.js:

chrome.runtime.onInstalled.addListener(() => {
async function getCurrentTab() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    let [tab] = await chrome.tabs.query(queryOptions);
    return tab;
}
alert(window.getCurrentTab());});

app.js:

chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);});

我也试过这样的代码:

;(function() {
var pushState = history.pushState;
var replaceState = history.replaceState;

history.pushState = function() {
    pushState.apply(history, arguments);
    window.dispatchEvent(new Event('pushstate'));
    window.dispatchEvent(new Event('locationchange'));
};

history.replaceState = function() {
    replaceState.apply(history, arguments);
    window.dispatchEvent(new Event('replacestate'));
    window.dispatchEvent(new Event('locationchange'));
};

window.addEventListener('popstate', function() {
    window.dispatchEvent(new Event('locationchange'))
});})();

window.addEventListener('locationchange', function(){
    console.log('onlocationchange event occurred!');
    alert(chrome.tabs.getCurrent(tab => tab.url));})

我在 app.js 中尝试过的所有内容我也在 background.js 中尝试过,反之亦然。要么我不明白如何跟踪扩展触发,要么它不起作用(可能是第二个)。通常,我尝试捕获 URL 更改事件,例如,切换选项卡或点击链接。好吧,到目前为止,什么都没有发生。其实第一个问题是这样的:如何做这样的Extension?

看来,我完全不明白这个话题,因此我也将非常感谢相关资料的链接。

那么,第二个问题是,将 URL 传递给 Windows 窗体应用程序的最佳方法是什么?

对不起,我的英语好像真的很糟糕。

【问题讨论】:

  • 您当前的代码无济于事。使用 chrome.webNavigation 事件监听器。

标签: javascript c# google-chrome google-chrome-extension


【解决方案1】:

在我的 app.js 中,我使用的是 current.Window 而不是 lastFocusedWindow

button_element.addEventListener('click', () => {    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        arr.push(tabs[0].url)
        localStorage.setItem("example", JSON.stringify(arr) )
        render(arr)
    })
})

这适用于将当前标签推送到本地存储

【讨论】:

    猜你喜欢
    • 2014-01-27
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 2015-12-04
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多