Redirect URL from local filesystem to internet with FireFox extension

扶醉桌前 提交于 2019-12-11 06:40:34

问题


I have several PDF files on my computer that contain links to other pages. Those links, however, direct you to the local filesystem instead of the internet. I.e. clicking the link opens the browser and takes you to file:///page instead of http://domain/page.

Getting these files modified to include the full URL is not an option.

I tried using available Firefox extensions to redirect the URL, but none worked, so I tried creating my own extension to do the same. What I've found so far is that the URL isn't accessible until the tab's "ready" event fires, but a page referring to a local file without the full path is always "uninitialized."

Here's my extension script, almost straight from https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs:

var tabs = require("sdk/tabs");
tabs.on('open', function(tab){
    tab.on('ready', function(tab){
        if (tab.url.indexOf("file:///page") != -1) {
            tab.url = tab.url.replace("file://", "https://domain");
        }
    });
});

Any ideas how to go about redirecting a page from a local file to another location?


回答1:


The following snippet works fine with me. In main.js:

var tabs = require("sdk/tabs");
tabs.on('ready', function(tab){
    var new_url = tab.url;
    if (tab.url.indexOf("file:///") != -1) {
        new_url = new_url.replace("file:///", "https://domain/");
        tab.url = new_url;
    }
});

Although, my Firefox didn't fire the ready event on my tab when the url is something like what you want. For example, when the url is file:///page/lala.pdf, firefox ignores the url and does not try to reach it. I believe Firefox wants a "real" path to load the page such as file:///C:page/lala.pdf.

I hope this will help you.




回答2:


The easiest way I've found to do this is actually from another StackOverflow answer... Get Content of Location Bar. Use the function in that answer to retrieve the URL and then redirect based on that. So I end up with the following:

var tabs = require("sdk/tabs");
tabs.on('open', function(tab){
    tab.on('activate', function(tab){
        var { getMostRecentWindow } = require("sdk/window/utils");
        var urlBar = getMostRecentWindow().document.getElementById('urlbar');
        if (urlBar.value.indexOf("file:///page/") != -1) {
            tab.url = urlBar.value.replace("file://", "https://domain");
        }
    });
});


来源:https://stackoverflow.com/questions/32873500/redirect-url-from-local-filesystem-to-internet-with-firefox-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!