Redirect URL from local filesystem to internet wit

2019-08-12 14:46发布

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?

2条回答
老娘就宠你
2楼-- · 2019-08-12 15:15

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.

查看更多
虎瘦雄心在
3楼-- · 2019-08-12 15:31

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");
        }
    });
});
查看更多
登录 后发表回答